package ystp.controller;

import jxl.SheetSettings;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import jxl.write.VerticalAlignment;
import org.apache.ibatis.session.RowBounds;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import ystp.dao.TyMapper;
import ystp.dao.TyjieguoMapper;
import ystp.dao.YsxiangmuMapper;
import ystp.model.*;
import ystp.service.YsrenyuanfenpeiService;
import ystp.service.YsuserService;
import ystp.service.YsxiangmuService;
import ystp.support.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.Boolean;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Controller
@RequestMapping("TyController")
public class TyController {
    public Logger log = LoggerFactory.getLogger(FujianJieguoController.class);
    @Value("${userfilepath}")
    private String userfilepath;
    @Autowired
    YsxiangmuService ddYsxiangmuService;
    @Autowired
    YsrenyuanfenpeiService ddYsrenyuanfenpeiService;
    @Autowired
    YsxiangmuMapper ddYsxiangmuMapper;
    @Autowired
    YsuserService ddYsuserService;
    @Autowired
    TyjieguoMapper tyjieguoMapper;
    @Autowired
    TyMapper tyMapper;

    /**
     * 导入所有项目人员名单
     * 功能说明：
     * 1. 读取Excel文件中的人员信息
     * 2. 将人员信息导入到所有项目中
     *
     * @param mmFileUrl 上传的Excel文件路径
     * @return 操作结果
     */
    @Transactional
    @RequestMapping("importAllProjectMembers")
    @ResponseBody
    public JsonResult<?> importAllProjectMembers(
            @RequestParam("fileurl") String mmFileUrl,
            HttpServletRequest request) {
        try {
            // 取出文档存放的根目录，并去除文件最后的斜杠
            if (userfilepath.endsWith("/")) {
                userfilepath = userfilepath.substring(0, userfilepath.length() - 1);
            }

            mmFileUrl = mmFileUrl.substring(mmFileUrl.indexOf("importexecl"));
            String url = userfilepath + "/" + mmFileUrl;
            Workbook book = null;

            File f = new File(url);
            InputStream in = new FileInputStream(f);

            String prefix = url.substring(url.lastIndexOf(".") + 1);
            if (prefix.equals("xls")) {
                book = new HSSFWorkbook(in);
            } else if (prefix.equals("xlsx")) {
                book = new XSSFWorkbook(in);
            } else {
                return JsonResult.getErrorResult("请上传xls或xlsx类型的文件！");
            }

            Sheet sheet = book.getSheetAt(0);
            DataFormatter dataFormatter = new DataFormatter();
            if (sheet == null) {
                return JsonResult.getErrorResult("请上传规范格式的EXCEL（确保上传数据在SHEET1中）！");
            }
            int rows = sheet.getPhysicalNumberOfRows();

            // 创建公式评估器
            FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();

            // 批量计算公式（确保所有公式都已计算）
            evaluator.evaluateAll();

            // 获取所有项目
            List<Ysxiangmu> xiangmuList = ddYsxiangmuService.findAll();
            if (xiangmuList.size() == 0) {
                return JsonResult.getErrorResult("没有可用的项目！");
            }

            // 记录导入结果
            int successCount = 0;
            int failCount = 0;
            List<String> failMessages = new ArrayList<>();

            // 读取Excel中的人员信息
            for (int i = 1; i < rows; i++) { // 行，从第2行开始（跳过表头）
                try {
                    String xuhao = dataFormatter.formatCellValue(sheet.getRow(i).getCell(0), evaluator);
                    String username = dataFormatter.formatCellValue(sheet.getRow(i).getCell(1), evaluator);
                    String buzhibie = dataFormatter.formatCellValue(sheet.getRow(i).getCell(2), evaluator);
                    String account = dataFormatter.formatCellValue(sheet.getRow(i).getCell(3), evaluator);
                    String password = dataFormatter.formatCellValue(sheet.getRow(i).getCell(4), evaluator);

                    // 检查必要字段是否为空
                    if (username == null || username.trim().isEmpty() ||
                            account == null || account.trim().isEmpty() ||
                            password == null || password.trim().isEmpty()) {
                        failCount++;
                        failMessages.add("第" + (i + 1) + "行数据不完整，跳过导入");
                        continue;
                    }

                    // 检查用户是否存在
                    Ysuser user = null;
                    if (ddYsuserService.isexistByAccount(account)) {
                        // 用户已存在，获取用户信息
                        List<Ysuser> userList = ddYsuserService.findByAccount(account);
                        if (userList != null && userList.size() > 0) {
                            user = userList.get(0);
                        }
                    } else {
                        // 用户不存在，创建新用户
                        user = new Ysuser();
                        user.setUserid(UUID.randomUUID().toString());
                        user.setUsername(username);
                        user.setBuzhibie(buzhibie);
                        user.setAccount(account);
                        user.setPassword(password);
                        user.setUsertype("zj");
                        user.setCreatetime(new Date());
                        try {
                            user.setOrdernum(Integer.parseInt(xuhao));
                        } catch (NumberFormatException e) {
                            user.setOrdernum(0);
                        }

                        // 添加用户
                        if (!ddYsuserService.add(user)) {
                            failCount++;
                            failMessages.add("第" + (i + 1) + "行用户添加失败：" + username);
                            continue;
                        }
                    }

                    // 将用户添加到所有项目中
                    int projectAddCount = 0;
                    for (Ysxiangmu xiangmu : xiangmuList) {
                        // 检查用户是否已经在项目中
                        List<Ysrenyuanfenpei> existFenpei = ddYsrenyuanfenpeiService
                                .findbyUserIDandXiangmuId(user.getUserid(), xiangmu.getXiangmuid());
                        if (existFenpei != null && existFenpei.size() > 0) {
                            // 用户已经在项目中，跳过
                            continue;
                        }

                        // 创建人员分配记录
                        Ysrenyuanfenpei fenpei = new Ysrenyuanfenpei();
                        fenpei.setId(UUID.randomUUID().toString());
                        fenpei.setXiangmuid(xiangmu.getXiangmuid());
                        fenpei.setUserid(user.getUserid());
                        fenpei.setIssubmit(0);
                        fenpei.setCreatetime(new Date());
                        HttpSession session = request.getSession();
                        if (session.getAttribute("Id") != null) {
                            fenpei.setCreateby(session.getAttribute("Id").toString());
                        }

                        // 添加人员分配
                        if (ddYsrenyuanfenpeiService.add(fenpei)) {
                            projectAddCount++;
                        }
                    }

                    if (projectAddCount > 0) {
                        successCount++;
                    } else {
                        failCount++;
                        failMessages.add("第" + (i + 1) + "行用户未能添加到任何项目：" + username);
                    }

                } catch (Exception e) {
                    failCount++;
                    failMessages.add("第" + (i + 1) + "行处理异常：" + e.getMessage());
                }
            }

            in.close();

            // 返回导入结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("successCount", successCount);
            resultMap.put("failCount", failCount);
            resultMap.put("failMessages", failMessages);
            return JsonResult.getSuccessResult(resultMap);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/importAllProjectMembers:error", e);
            return JsonResult.getErrorResult("TyController/importAllProjectMembers:error " + e.getMessage());
        }
    }

    @RequestMapping("deleteXiangmu")
    @ResponseBody
    @Transactional
    public JsonResult<?> deleteXiangmu(@RequestParam("xianmguid") String ppxianmguId) {
        try {
            // 1. 删除相关人员分配
            ddYsrenyuanfenpeiService.deleteByXiangmuid(ppxianmguId);

            // 2. 删除ty表中相关记录
            TyExample tyExample = new TyExample();
            tyExample.createCriteria().andXiangmuidEqualTo(ppxianmguId);
            tyMapper.deleteByExample(tyExample);

            // 3. 删除tyjieguo表中相关记录
            TyjieguoExample tyjieguoExample = new TyjieguoExample();
            tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxianmguId);
            tyjieguoMapper.deleteByExample(tyjieguoExample);

            // 4. 更新项目状态为删除状态
            YsxiangmuExample mmexample = new YsxiangmuExample();
            mmexample.createCriteria().andXiangmuidEqualTo(ppxianmguId);
            ddYsxiangmuMapper.deleteByExample(mmexample);

            return JsonResult.getSuccessResult("删除项目成功");

        } catch (Exception e) {
            e.printStackTrace();
            log.error("xiangmu/delete:error", e);
            return JsonResult.getErrorResult("xiangmu/delete:error " + e.getMessage());
        }
    }

    /**
     * 开启项目二轮投票
     * 
     * 功能说明：
     * 1. 基于一轮投票项目创建二轮投票项目
     * 2. 复制人员分配信息到新项目
     * 3. 筛选符合条件的表决项进入二轮投票
     * 
     * @param ppxiangmuId      原项目ID
     * @param ppxiangmuleixing 项目类型
     * @return 操作结果
     */
    @RequestMapping("toAddRoundSecond")
    @ResponseBody
    public JsonResult<?> toAddRoundSecond(@RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing) {
        // 查询原项目的表决列表
        List<Ty> mmTyList = tyMapper.findBiaojuelist(ppxiangmuId, "");
        // 查询原项目信息
        Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppxiangmuId);
        if (mmYsxiangmu == null) {
            return JsonResult.getErrorResult("项目不存在");
        }

        // 创建新的二轮投票项目
        Ysxiangmu newYsxiangmu = new Ysxiangmu();
        String newXiangmuid = UUID.randomUUID().toString();
        if (ppxiangmuId.equals("437c4666-f295-4ba6-b0cc-0040d60f9b42")) {
            newXiangmuid = "444c4666-f295-4ba6-b0cc-0040d60f9b42";
        }
        newYsxiangmu.setXiangmuid(newXiangmuid);
        newYsxiangmu.setXiangmuname(mmYsxiangmu.getXiangmuname() + "二轮投票");
        newYsxiangmu.setXiangmuleixing("219");
        newYsxiangmu.setIsactived(0);
        newYsxiangmu.setLunci(2);
        newYsxiangmu.setStatus(100);
        newYsxiangmu.setCreatetime(new Date());
        newYsxiangmu.setCreateby(mmYsxiangmu.getCreateby());
        newYsxiangmu.setMeetingtime(mmYsxiangmu.getMeetingtime());
        newYsxiangmu.setTongguoshu(mmYsxiangmu.getTongguoshu());
        ddYsxiangmuService.add(newYsxiangmu);

        // 复制原项目的人员分配信息到新项目
        List<Ysrenyuanfenpei> mmUserList = ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuId);
        for (Ysrenyuanfenpei item : mmUserList) {
            Ysrenyuanfenpei newYsrenyuanfenpei = new Ysrenyuanfenpei(item);
            newYsrenyuanfenpei.setId(UUID.randomUUID().toString());
            newYsrenyuanfenpei.setXiangmuid(newXiangmuid);
            newYsrenyuanfenpei.setCreatetime(new Date());
            newYsrenyuanfenpei.setIssubmit(0); // 重置提交状态
            ddYsrenyuanfenpeiService.add(newYsrenyuanfenpei);
        }

        // 查询原项目的投票结果
        TyjieguoExample tyjieguoExample = new TyjieguoExample();
        tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuId);
        List<Tyjieguo> jieguoList = tyjieguoMapper.selectByExample(tyjieguoExample);
        mmTyList.stream().forEach(x -> {
            long mmpiaoshu = jieguoList.stream()
                    .filter(y -> y.getDetailid().equals(x.getId()) && y.getResult().equals("1"))
                    .filter(distinctByKey(y -> y.getUserid())).count();
            x.setPiaoshu(String.valueOf(mmpiaoshu));
        });

        // 创建新的表决项列表
        List<Ty> newTyList = new ArrayList<>();
        // 计算通过票数阈值（项目类型对应的通过比例 * 总人数）
        Double mm = (TyConfig.getPassCount(mmYsxiangmu.getXiangmuleixing())) * mmUserList.size();
        Double mmTongguopiaoshu = mm;
        int passcount = 0;
        // 筛选符合条件的表决项进入二轮投票
        for (Ty item : mmTyList) {
            Ty newTy = new Ty(item);
            newTy.setId(UUID.randomUUID().toString());
            newTy.setXiangmuid(newXiangmuid);
            newTy.setCreatetime(new Date());
            newTy.setText21(item.getPiaoshu());
            newTy.setText22(String.valueOf(mmUserList.size()));
            newTy.setText19("111");
            newTy.setOrdernumber(item.getOrdernumber() + Integer.parseInt(item.getPiaoshu() + 1) * -1000);
            // 统计该表决项的通过票数（去重）
            long mmpiaoshu = jieguoList.stream()
                    .filter(x -> x.getDetailid().equals(item.getId()) && x.getResult().equals("1"))
                    .filter(distinctByKey(x -> x.getUserid())).count();
            newTy.setPiaoshu(String.valueOf(mmpiaoshu));
            // 如果票数超过阈值，不进入二轮投票
            if (mmpiaoshu > mmTongguopiaoshu) {
                passcount++;
                continue;
            } else {
                newTyList.add(newTy);
            }
        }
        int needcount = TyConfig.Rule_PinzhongPinguiNumsp(ppxiangmuleixing,
                mmTyList.get(0).getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))).getNum();
        int poolcount = (needcount - passcount) * 2;
        int totalcount = countAll(ppxiangmuleixing, ppxiangmuId);
        int failcount = totalcount - passcount;
        if (failcount > poolcount && needcount > 0) {
            newTyList = newTyList.stream().sorted((a, b) -> {
                // 将票数字符串转换为数字进行比较
                int votesA = 0;
                int votesB = 0;

                if (a.getPiaoshu() != null && a.getPiaoshu().contains("/")) {
                    votesA = Integer.parseInt(a.getPiaoshu().split("/")[0]);
                }

                if (b.getPiaoshu() != null && b.getPiaoshu().contains("/")) {
                    votesB = Integer.parseInt(b.getPiaoshu().split("/")[0]);
                }

                return Integer.compare(votesA, votesB);
            }).limit(poolcount).collect(Collectors.toList());
        }
        // 批量插入新的表决项
        int result = tyMapper.insertBatch(newTyList);

        // 返回操作结果
        if (result > 0) {
            return JsonResult.getSuccessResult("添加二轮投票成功");
        } else {
            return JsonResult.getErrorResult("添加二轮投票失败");
        }
    }

    @Transactional
    @RequestMapping("importExel")
    @ResponseBody
    public JsonResult<?> importExel(
            @RequestParam("xianmguid") String ppxianmguid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            @RequestParam("fileurl") String mmFileUrl,
            HttpServletRequest request) {
        try {
            TyExample mmExample = new TyExample();
            mmExample.createCriteria().andXiangmuidEqualTo(ppxianmguid);
            int isexit = tyMapper.selectByExample(mmExample).size();
            if (isexit > 0) {
                return JsonResult.getErrorResult("导入失败！该项目已存在数据，请删除后再导入。");
            }

            // 取出文档存放的根目录，并去除文件最后的斜杠
            if (userfilepath.endsWith("/")) {
                userfilepath = userfilepath.substring(0, userfilepath.length() - 1);
            }

            mmFileUrl = mmFileUrl.substring(mmFileUrl.indexOf("importexecl"));
            String url = userfilepath + "/" + mmFileUrl;
            Workbook book = null;

            File f = new File(url);
            InputStream in = new FileInputStream(f);

            String prefix = url.substring(url.lastIndexOf(".") + 1);
            if (prefix.equals("xls")) {
                book = new HSSFWorkbook(in);
            } else if (prefix.equals("xlsx")) {
                book = new XSSFWorkbook(in);
            } else {
                return JsonResult.getErrorResult("请上传xls或xlsx类型的文件！");
            }

            Sheet sheet = book.getSheetAt(0);
            DataFormatter dataFormatter = new DataFormatter();
            if (sheet == null) {
                return JsonResult.getErrorResult("请上传规范格式的EXCEL（确保上传数据在SHEET1中）！");
            }
            int rows = sheet.getPhysicalNumberOfRows();
            // 创建公式评估器
            FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();

            // 批量计算公式（确保所有公式都已计算）
            evaluator.evaluateAll();
            int result = -1;
            {
                List<Ty> mmReturnList = new ArrayList<>();
                for (int i = TyConfig.getExelStartLine(ppxiangmuleixing); i < rows; i++) { // 行
                    Ty itme = new Ty();
                    itme.setId(UUID.randomUUID().toString());
                    itme.setXiangmuid(ppxianmguid);
                    for (int j = 0; j < TyConfig.getExel(ppxiangmuleixing); j++) {
                        itme.setAttribute("text" + (j + 1),
                                dataFormatter.formatCellValue(sheet.getRow(i).getCell(j), evaluator));
                    }
                    itme.setIsvote(1);
                    itme.setOrdernumber(i - 1);
                    itme.setCreatetime(new Date());
                    mmReturnList.add(itme);
                }
                result = tyMapper.insertBatch(mmReturnList);
            }

            in.close();

            if (result == 0) {
                return JsonResult.getErrorResult("插入失败！");
            }
            return JsonResult.getSuccessResult("");

        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController -> importExel: " + e.getMessage());
            return JsonResult.getErrorResult("获取项目中的数据失败！");
        }
    }

    @RequestMapping("bohui")
    @ResponseBody
    public JsonResult<?> bohui(@RequestParam("id") String ppId) {
        try {

            Ysrenyuanfenpei mmRenyuanfenpei = new Ysrenyuanfenpei();
            mmRenyuanfenpei.setId(ppId);
            mmRenyuanfenpei.setIssubmit(0);
            return ddYsrenyuanfenpeiService.updateByPrimaryKeySelective(mmRenyuanfenpei)
                    ? JsonResult.getSuccessResult("驳回成功")
                    : JsonResult.getErrorResult("驳回失败");

        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/bohui:error", e);
            return JsonResult.getErrorResult("TyController/bohui:error " + e.getMessage());
        }
    }

    @RequestMapping("/ViewAll")
    public String ViewAll(String xiangmuid, String xiangmuleixing, HttpServletRequest request, ModelMap map) {

        if (isLogin(request)) {
            map.put("xiangmuId", xiangmuid);
            map.put("xiangmuLeixing", xiangmuleixing);
            return "main/view_ty";
        } else {
            return "main/login";
        }

    }

    @RequestMapping("/HuizongbiaoView")
    public String HuizongbiaoView(String xiangmuid, String xiangmuleixing, HttpServletRequest request, ModelMap map) {

        if (isLogin(request)) {
            map.put("xiangmuId", xiangmuid);
            map.put("xiangmuLeixing", xiangmuleixing);
            return "main/Huizongbiaoview";
        } else {
            return "main/login";
        }

    }

    @RequestMapping("bindHuizongbiaoviewList")
    @ResponseBody
    public JsonResult<?> bindHuizongbiaoviewList(@RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("pageindex") int ppPageIndex,
            @RequestParam("pagesize") int ppPageSize, @RequestParam("xiangmuleixing") String ppxiangmuleixing) {

        try {
            Map<String, Object> mmReturnMap = new HashMap<String, Object>();
            Integer mmCount = 0;
            List<Ysrenyuanfenpei> mmUserList = ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuId);
            Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppxiangmuId);
            Double mm = (TyConfig.getPassCount(ppxiangmuleixing)) * mmUserList.size();
            Double mmTongguopiaoshu = mm;
            mmCount = countAll(ppxiangmuleixing, ppxiangmuId);
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 1) {

                int offset = (ppPageIndex - 1) * ppPageSize;
                RowBounds rowBounds = new RowBounds(offset, ppPageSize);
                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, "", rowBounds);
                TyjieguoExample tyjieguoExample = new TyjieguoExample();
                tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuId);
                List<Tyjieguo> jieguoList = tyjieguoMapper.selectByExample(tyjieguoExample);
                for (Ty item : mmPinguiAll) {
                    long mmpiaoshu = jieguoList.stream()
                            .filter(x -> x.getDetailid().equals(item.getId()) && x.getResult().equals("1"))
                            .filter(distinctByKey(x -> x.getUserid())).count();

                    String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                    String mmJieguotext = "";

                    if (mmpiaoshu > mmTongguopiaoshu) {
                        mmJieguotext = "通过";
                    } else {
                        mmJieguotext = "不通过";

                    }
                    item.setResult(mmJieguotext);
                    item.setPiaoshu(piaoshutext);
                }
                mmReturnMap.put("pinguiList", mmPinguiAll);
            }
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 2) {
                List<Map<String, Object>> mmPinpaiList = new ArrayList<>();
                TyjieguoExample tyjieguoExample = new TyjieguoExample();
                tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuId);
                List<Tyjieguo> jieguoList = tyjieguoMapper.selectByExample(tyjieguoExample);
                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, "");
                List<Ty> mmPinpailist = mmPinguiAll.stream()
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                        .collect(Collectors.toList());
                for (int i = 0; i < mmPinpailist.size(); i++) {
                    int mmPinguiHebingshu = 0;
                    Ty pinpaiONE = mmPinpailist.get(i);
                    Map<String, Object> mmPinguiMap = new HashMap<>();
                    mmPinguiMap.put("pinpaione", pinpaiONE);

                    List<Ty> mmPinguiList = mmPinguiAll.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                    .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    if (mmPinguiList.size() > 0) {
                        mmPinguiHebingshu = mmPinguiList.size();
                    } else {
                        mmPinguiHebingshu = mmPinguiHebingshu + 1;
                    }
                    for (Ty item : mmPinguiList) {
                        long mmpiaoshu = jieguoList.stream()
                                .filter(x -> x.getDetailid().equals(item.getId()) && x.getResult().equals("1"))
                                .filter(distinctByKey(x -> x.getUserid())).count();

                        String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                        String mmJieguotext = "";

                        if (mmpiaoshu > mmTongguopiaoshu) {
                            mmJieguotext = "通过";
                        } else {
                            mmJieguotext = "不通过";

                        }

                        item.setResult(mmJieguotext);
                        item.setPiaoshu(piaoshutext);
                    }
                    mmPinguiMap.put("pinguiList", mmPinguiList);
                    mmPinguiMap.put("pinguihebinghang", mmPinguiHebingshu);
                    mmPinpaiList.add(mmPinguiMap);
                }

                mmReturnMap.put("pinpaiList", mmPinpaiList);
                mmReturnMap.put("pinpaixuhao", TyConfig.getPinpai(ppxiangmuleixing));
            }
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 3) {
                List<Map<String, Object>> mmPinzhongList = new ArrayList<>();
                TyjieguoExample tyjieguoExample = new TyjieguoExample();
                tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuId);
                List<Tyjieguo> jieguoList = tyjieguoMapper.selectByExample(tyjieguoExample);
                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, "");
                List<Ty> mmPinguiAllcp = tyMapper.findBiaojuelist(ppxiangmuId, "");
                // 修改：只按照品种字段进行去重，不再同时按品牌去重
                List<Ty> mmPinzhonglist = mmPinguiAll.stream()
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                        .collect(Collectors.toList());
                for (Ty item : mmPinguiAllcp) {
                    long mmpiaoshu = jieguoList.stream()
                            .filter(x -> x.getDetailid().equals(item.getId()) && x.getResult().equals("1"))
                            .filter(distinctByKey(x -> x.getUserid())).count();

                    String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                    String mmJieguotext = "";

                    if (mmpiaoshu > mmTongguopiaoshu) {
                        mmJieguotext = "通过";
                    } else {
                        mmJieguotext = "不通过";
                    }
                    item.setResult(mmJieguotext);
                    item.setPiaoshu(piaoshutext);
                }
                if (ppxiangmuleixing.equals("219") && mmYsxiangmu.getLunci() == 1) {
                    int passcount = (int) mmPinguiAllcp.stream().filter(item -> "通过".equals(item.getResult())).count();
                    int totalcount = countAll(ppxiangmuleixing, ppxiangmuId);
                    String pinzhongxuhao = mmPinguiAllcp.get(0).getAttribute(TyConfig.getPinzhong(ppxiangmuleixing));
                    int needcount = TyConfig.Rule_PinzhongPinguiNumsp(ppxiangmuleixing, pinzhongxuhao).getNum();
                    int num = needcount;
                    if (passcount > num && num != 0) {
                        // 直接在mmPinguiAll中筛选和操作
                        // 获取通过的品规列表
                        List<Ty> passedList = mmPinguiAllcp.stream()
                                .filter(item -> "通过".equals(item.getResult()))
                                .collect(Collectors.toList());

                        // 先将列表反转，这样原本靠后的项目会排在前面
                        Collections.reverse(passedList);

                        // 按照票数从低到高排序，票数相同时保持反转后的顺序（原本靠后的排在前面）
                        passedList.sort((item1, item2) -> {
                            // 获取票数
                            int votes1 = 0;
                            int votes2 = 0;

                            String piaoshu1 = item1.getPiaoshu();
                            if (piaoshu1 != null && piaoshu1.contains("/")) {
                                votes1 = Integer.parseInt(piaoshu1.split("/")[0]);
                            }

                            String piaoshu2 = item2.getPiaoshu();
                            if (piaoshu2 != null && piaoshu2.contains("/")) {
                                votes2 = Integer.parseInt(piaoshu2.split("/")[0]);
                            }

                            // 按票数升序排列
                            return votes1 - votes2;
                        });

                        // 计算需要设置为不通过的数量
                        int needToFailCount = passcount
                                - num;
                        // 将票数最低的needToFailCount个品规设为不通过
                        for (int i = 0; i < needToFailCount; i++) {
                            Ty item = passedList.get(i);
                            item.setResult("不通过");

                            // 确保在mmPinguiAll中也更新对应项的状态
//                            for (Ty originalItem : mmPinguiAllcp) {
//                                if (originalItem.getId().equals(item.getId())) {
//                                    originalItem.setResult("不通过");
//                                    break;
//                                }
//                            }
                        }
                        // passcount = needcount;
                    }
                    mmReturnMap.put("passcount", passcount);
                    mmReturnMap.put("totalcount", totalcount);
                    mmReturnMap.put("needcount", needcount);
                    mmReturnMap.put("keshi", mmPinguiAllcp.get(0).getText2());
                    if (mmYsxiangmu.getXiangmuid().equals("437c4666-f295-4ba6-b0cc-0040d60f9b42")
                            || mmYsxiangmu.getXiangmuid().equals("444c4666-f295-4ba6-b0cc-0040d60f9b42")) {
                        mmReturnMap.put("keshi", mmPinguiAllcp.get(0).getText2() + "," + mmPinguiAllcp.get(1).getText2()
                                + "," + mmPinguiAllcp.get(2).getText2() + "共");
                    }
                } else if (ppxiangmuleixing.equals("219") && mmYsxiangmu.getLunci() == 2) {
                    int[] t = VotePinguiMax(ppxiangmuId, ppxiangmuleixing, "");
                    int passcount = (int) mmPinguiAllcp.stream().filter(item -> "通过".equals(item.getResult())).count();
                    int totalcount = t[2];
                    int needcount = t[1];
                    mmReturnMap.put("passcount", passcount);
                    mmReturnMap.put("totalcount", totalcount);
                    mmReturnMap.put("needcount", needcount);
                    mmReturnMap.put("keshi", mmPinguiAllcp.get(0).getText2());
                    if (mmYsxiangmu.getXiangmuid().equals("437c4666-f295-4ba6-b0cc-0040d60f9b42")
                            || mmYsxiangmu.getXiangmuid().equals("444c4666-f295-4ba6-b0cc-0040d60f9b42")) {
                        mmReturnMap.put("keshi", mmPinguiAllcp.get(0).getText2() + "," + mmPinguiAllcp.get(1).getText2()
                                + "," + mmPinguiAllcp.get(2).getText2() + "共");
                    }
                }
                for (int i = 0; i < mmPinzhonglist.size(); i++) {
                    int mmPinpaiHebingshu = 0;
                    List<Map<String, Object>> mmPinpaiList = new ArrayList<>();
                    Ty pinzhongONE = mmPinzhonglist.get(i);
                    Map<String, Object> mmPinpaiMap = new HashMap<>();
                    // 修改：使用pinzhongone而不是pinguione
                    mmPinpaiMap.put("pinzhongone", pinzhongONE);
                    // 修改：只按当前品种筛选，然后按品牌去重
                    List<Ty> mmPinpailist = mmPinguiAll.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                    .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                            .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    if (mmPinpailist.size() > 0) {
                        mmPinpaiHebingshu = mmPinpailist.size();
                    } else {
                        mmPinpaiHebingshu = mmPinpaiHebingshu + 1;
                    }
                    for (int j = 0; j < mmPinpailist.size(); j++) {
                        int mmPinguiHebingshu = 0;
                        Ty pinpaiONE = mmPinpailist.get(j);
                        Map<String, Object> mmPinguiMap = new HashMap<>();
                        mmPinguiMap.put("pinpaione", pinpaiONE);

                        // 修改：按当前品种和品牌同时筛选
                        List<Ty> mmPinguiList = mmPinguiAll.stream()
                                .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                        .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                                .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                        .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                                .collect(Collectors.toList());
                        if (mmPinguiList.size() > 0) {
                            mmPinguiHebingshu = mmPinguiList.size();
                        } else {
                            mmPinguiHebingshu = mmPinguiHebingshu + 1;
                        }
                        for (Ty item : mmPinguiList) {
                            long mmpiaoshu = jieguoList.stream()
                                    .filter(x -> x.getDetailid().equals(item.getId()) && x.getResult().equals("1"))
                                    .filter(distinctByKey(x -> x.getUserid())).count();

                            String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                            String mmJieguotext = "";

                            if (mmpiaoshu > mmTongguopiaoshu) {
                                mmJieguotext = "通过";
                                // if (ppxiangmuleixing.equals("219") && mmYsxiangmu.getLunci() == 1) {
                                // if (mmPinguiAllcp.stream().filter(a ->
                                // a.getId().equals(item.getId())).findFirst()
                                // .get().getResult().equals("不通过")) {
                                // mmJieguotext = "剔除";
                                // }
                                // }

                            } else {
                                mmJieguotext = "不通过";

                            }

                            item.setResult(mmJieguotext);
                            item.setPiaoshu(piaoshutext);
                        }
                        mmPinguiMap.put("pinguiList", mmPinguiList);
                        mmPinguiMap.put("pinguihebinghang", mmPinguiHebingshu);
                        mmPinpaiList.add(mmPinguiMap);
                    }
                    mmPinpaiMap.put("pinpaiList", mmPinpaiList);
                    mmPinpaiMap.put("pinguihebinghang", mmPinpaiHebingshu);
                    mmPinzhongList.add(mmPinpaiMap);
                }

                mmReturnMap.put("pinzhongList", mmPinzhongList);
                mmReturnMap.put("pinpaixuhao", TyConfig.getPinpai(ppxiangmuleixing));
                mmReturnMap.put("pinzhongxuhao", TyConfig.getPinzhong(ppxiangmuleixing));
            }
            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
            mmReturnMap.put("PageInfo", mmPageInfo);
            mmReturnMap.put("Xunhuan", TyConfig.getXunhuan(ppxiangmuleixing));
            mmReturnMap.put("getCount", TyConfig.getCount(ppxiangmuleixing));
            mmReturnMap.put("lunci", mmYsxiangmu.getLunci());
            return JsonResult.getSuccessResult(mmReturnMap);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("HuizongbiaoView/bindHuizongbiaoviewList:error", e);
            return JsonResult.getErrorResult("HuizongbiaoView/bindHuizongbiaoviewList:error " + e.getMessage());
        }
    }

    public boolean deleteByxiangmuId(String ppxiangmuId, String ppxiangmuleixing) {
        TyExample mmExample = new TyExample();
        mmExample.createCriteria().andXiangmuidEqualTo(ppxiangmuId);
        return tyMapper.deleteByExample(mmExample) >= 0;
    }

    @RequestMapping("delete")
    @ResponseBody
    public JsonResult<?> delete(@RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing) {
        try {
            return deleteByxiangmuId(ppxiangmuId, ppxiangmuleixing) == true ? JsonResult.getSuccessResult("删除材料成功")
                    : JsonResult.getErrorResult("删除材料失败");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/delete:error", e);
            return JsonResult.getErrorResult("TyController/delete:error " + e.getMessage());
        }
    }

    @RequestMapping("bindviewList")
    @ResponseBody
    public JsonResult<?> bindviewList(@RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("pageindex") int ppPageIndex,
            @RequestParam("pagesize") int ppPageSize, @RequestParam("xiangmuleixing") String ppxiangmuleixing) {
        try {
            Map<String, Object> mmReturnMap = new HashMap<String, Object>();
            Integer mmCount = countAll(ppxiangmuleixing, ppxiangmuId);
            List<Ysrenyuanfenpei> mmUserList = ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuId);
            Double mm = (TyConfig.getPassCount(ppxiangmuleixing)) * mmUserList.size();
            Double mmTongguopiaoshu = mm;
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 1) {
                int offset = (ppPageIndex - 1) * ppPageSize;
                RowBounds rowBounds = new RowBounds(offset, ppPageSize);
                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, "", rowBounds);

                mmReturnMap.put("pinguiList", mmPinguiAll);
            }
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 2) {
                List<Map<String, Object>> mmPinpaiList = new ArrayList<>();

                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, "");
                List<Ty> mmPinpailist = mmPinguiAll.stream()
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                        .collect(Collectors.toList());
                for (int i = 0; i < mmPinpailist.size(); i++) {
                    int mmPinguiHebingshu = 0;
                    Ty pinpaiONE = mmPinpailist.get(i);
                    Map<String, Object> mmPinguiMap = new HashMap<>();
                    mmPinguiMap.put("pinpaione", pinpaiONE);

                    List<Ty> mmPinguiList = mmPinguiAll.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                    .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    if (mmPinguiList.size() > 0) {
                        mmPinguiHebingshu = mmPinguiList.size();
                    } else {
                        mmPinguiHebingshu = mmPinguiHebingshu + 1;
                    }
                    mmPinguiMap.put("pinguiList", mmPinguiList);
                    mmPinguiMap.put("pinguihebinghang", mmPinguiHebingshu);
                    mmPinpaiList.add(mmPinguiMap);
                }

                mmReturnMap.put("pinpaiList", mmPinpaiList);
                mmReturnMap.put("pinpaixuhao", TyConfig.getPinpai(ppxiangmuleixing));
            }
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 3) {
                List<Map<String, Object>> mmPinzhongList = new ArrayList<>();
                TyjieguoExample tyjieguoExample = new TyjieguoExample();
                tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuId);
                List<Tyjieguo> jieguoList = tyjieguoMapper.selectByExample(tyjieguoExample);
                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, "");
                // 修改：只按照品种字段进行去重，不再同时按品牌去重
                List<Ty> mmPinzhonglist = mmPinguiAll.stream()
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                        .collect(Collectors.toList());

                for (int i = 0; i < mmPinzhonglist.size(); i++) {
                    int mmPinpaiHebingshu = 0;
                    List<Map<String, Object>> mmPinpaiList = new ArrayList<>();
                    Ty pinzhongONE = mmPinzhonglist.get(i);
                    Map<String, Object> mmPinpaiMap = new HashMap<>();
                    // 修改：使用pinzhongone而不是pinguione
                    mmPinpaiMap.put("pinzhongone", pinzhongONE);
                    // 修改：只按当前品种筛选，然后按品牌去重
                    List<Ty> mmPinpailist = mmPinguiAll.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                    .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                            .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    if (mmPinpailist.size() > 0) {
                        mmPinpaiHebingshu = mmPinpailist.size();
                    } else {
                        mmPinpaiHebingshu = mmPinpaiHebingshu + 1;
                    }
                    for (int j = 0; j < mmPinpailist.size(); j++) {
                        int mmPinguiHebingshu = 0;
                        Ty pinpaiONE = mmPinpailist.get(j);
                        Map<String, Object> mmPinguiMap = new HashMap<>();
                        mmPinguiMap.put("pinpaione", pinpaiONE);

                        // 修改：按当前品种和品牌同时筛选
                        List<Ty> mmPinguiList = mmPinguiAll.stream()
                                .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                        .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                                .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                        .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                                .collect(Collectors.toList());
                        if (mmPinguiList.size() > 0) {
                            mmPinguiHebingshu = mmPinguiList.size();
                        } else {
                            mmPinguiHebingshu = mmPinguiHebingshu + 1;
                        }
                        for (Ty item : mmPinguiList) {
                            long mmpiaoshu = jieguoList.stream()
                                    .filter(x -> x.getDetailid().equals(item.getId()) && x.getResult().equals("1"))
                                    .filter(distinctByKey(x -> x.getUserid())).count();

                            String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                            String mmJieguotext = "";

                            if (mmpiaoshu > mmTongguopiaoshu) {
                                mmJieguotext = "通过";
                            } else {
                                mmJieguotext = "不通过";

                            }

                            item.setResult(mmJieguotext);
                            item.setPiaoshu(piaoshutext);
                        }
                        mmPinguiMap.put("pinguiList", mmPinguiList);
                        mmPinguiMap.put("pinguihebinghang", mmPinguiHebingshu);
                        mmPinpaiList.add(mmPinguiMap);
                    }
                    mmPinpaiMap.put("pinpaiList", mmPinpaiList);
                    mmPinpaiMap.put("pinguihebinghang", mmPinpaiHebingshu);
                    mmPinzhongList.add(mmPinpaiMap);
                }

                mmReturnMap.put("pinzhongList", mmPinzhongList);
                mmReturnMap.put("pinpaixuhao", TyConfig.getPinpai(ppxiangmuleixing));
                mmReturnMap.put("pinzhongxuhao", TyConfig.getPinzhong(ppxiangmuleixing));
            }
            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
            mmReturnMap.put("PageInfo", mmPageInfo);
            mmReturnMap.put("Xunhuan", TyConfig.getXunhuan(ppxiangmuleixing));
            mmReturnMap.put("getCount", TyConfig.getCount(ppxiangmuleixing));
            return JsonResult.getSuccessResult(mmReturnMap);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("Fujian/bindviewList:error", e);
            return JsonResult.getErrorResult("Fujian/bindviewList:error " + e.getMessage());
        }
    }

    public int countPass(String ppxiangmuleixing, String ppxiangmuId, String mmUserId) {
        int pass = 0;
        switch (TyConfig.getCount(ppxiangmuleixing)) {
            case 1:
                pass = tyMapper.countPinguiPass(ppxiangmuId, mmUserId);
                break;
            case 2:
                pass = tyMapper.countPinpaiPass(ppxiangmuId, mmUserId, TyConfig.getPinpai(ppxiangmuleixing));
                break;
            case 3:
                pass = tyMapper.countPinzhongPass(ppxiangmuId, mmUserId,
                        TyConfig.getPinzhong(ppxiangmuleixing));
                break;
        }
        return pass;
    }

    public int countAll(String ppxiangmuleixing, String ppxiangmuId) {
        int pass = 0;
        switch (TyConfig.getCount(ppxiangmuleixing)) {
            case 1:
                pass = tyMapper.countPinguiAll(ppxiangmuId);
                break;
            case 2:
                pass = tyMapper.countPinpaiAll(ppxiangmuId, TyConfig.getPinpai(ppxiangmuleixing));
                break;
            case 3:
                pass = tyMapper.countPinzhongAll(ppxiangmuId, TyConfig.getPinzhong(ppxiangmuleixing),
                        TyConfig.getPinzhong(ppxiangmuleixing));
                break;
        }
        return pass;
    }

    @RequestMapping("getjindulist")
    @ResponseBody
    public JsonResult<?> getjindulist(@RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("xiangmuLeixing") String ppxiangmuleixing) {
        try {
            List<Map<String, Object>> mmJindulist = new ArrayList<>();
            Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppxiangmuId);

            List<Map<String, Object>> mmUserList = ddYsrenyuanfenpeiService.findRenyuanFenpeiByXiangmuId(ppxiangmuId);
            for (Map<String, Object> ysrenyuanfenpei : mmUserList) {
                Map<String, Object> mmMap = new HashMap<String, Object>();
                String mmUserId = ysrenyuanfenpei.get("userid").toString();
                Ysuser mmYsuser = ddYsuserService.findOne(mmUserId);
                String mmUserName = mmYsuser.getUsername();

                int mmPass = countPass(ppxiangmuleixing, ppxiangmuId, mmUserId);
                int mmtotalshu = countAll(ppxiangmuleixing, ppxiangmuId);

                String mmShifoutijiao = "";
                if ("1".equals(ysrenyuanfenpei.get("issubmit").toString())) {
                    mmShifoutijiao = "是";
                } else {
                    mmShifoutijiao = "否";
                }

                mmMap.put("username", mmUserName);
                mmMap.put("shengchanqiyeshu", mmPass + "/" + mmtotalshu);
                mmMap.put("shifoutijiao", mmShifoutijiao);
                mmJindulist.add(mmMap);

            }
            return JsonResult.getSuccessResult(mmJindulist);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/getjindulist:error", e);
            return JsonResult.getErrorResult("TyController/getjindulist:error " + e.getMessage());
        }
    }

    // 待修改
    public boolean VotePinguiAndPinpaiOnlyONE(String ppxiangmuleixing, String ppdetailId, String ppxiangmuid,
            String ppuserId) {
        Ty choose = tyMapper.selectByPrimaryKey(ppdetailId);
        String pinpaixuhao = choose.getAttribute(TyConfig.getPinpai(ppxiangmuleixing));
        TyExample tyExample = new TyExample();
        tyExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid)
                .andEqualTo(TyConfig.getPinpai(ppxiangmuleixing), pinpaixuhao).andIsvoteEqualTo(1);
        List<Ty> pinguilist = tyMapper.selectByExample(tyExample);
        List<String> ids = pinguilist.stream().map(x -> x.getId()).collect(Collectors.toList());
        TyjieguoExample tyjieguoExample = new TyjieguoExample();
        tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid).andUseridEqualTo(ppuserId).andDetailidIn(ids)
                .andResultEqualTo("1");
        int count = tyjieguoMapper.countByExample(tyjieguoExample);
        if (count == 0)
            return false;
        else
            return true;
    }

    public boolean VotePinguiAndPinpaiOnlyNum(String ppdetailId, String ppxiangmuid, String ppuserId,
            String ppxiangmuleixing) {
        Ty choose = tyMapper.selectByPrimaryKey(ppdetailId);
        String pinpaixuhao = choose.getAttribute(TyConfig.getPinpai(ppxiangmuleixing));
        TyExample tyExample = new TyExample();
        tyExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid).andIsvoteEqualTo(1)
                .andEqualTo(TyConfig.getPinpai(ppxiangmuleixing), pinpaixuhao);
        List<Ty> pinguilist = tyMapper.selectByExample(tyExample);
        List<String> ids = pinguilist.stream().map(x -> x.getId()).collect(Collectors.toList());
        TyjieguoExample tyjieguoExample = new TyjieguoExample();
        tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid).andUseridEqualTo(ppuserId).andDetailidIn(ids)
                .andResultEqualTo("1");
        int count = tyjieguoMapper.countByExample(tyjieguoExample);
        return count >= TyConfig.Rule_PinpaiPinguiNum(ppxiangmuleixing, pinpaixuhao).getNum();
    }

    public boolean VotePinguiAndPinzhongOnlyNum(String ppdetailId, String ppxiangmuid, String ppuserId,
            String ppxiangmuleixing) {
        Ty choose = tyMapper.selectByPrimaryKey(ppdetailId);
        String pinzhongxuhao = choose.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing));
        TyExample tyExample = new TyExample();
        tyExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid).andIsvoteEqualTo(1)
                .andEqualTo(TyConfig.getPinzhong(ppxiangmuleixing), pinzhongxuhao);
        List<Ty> pinguilist = tyMapper.selectByExample(tyExample);
        List<String> ids = pinguilist.stream().map(x -> x.getId()).collect(Collectors.toList());
        TyjieguoExample tyjieguoExample = new TyjieguoExample();
        tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid).andUseridEqualTo(ppuserId).andDetailidIn(ids)
                .andResultEqualTo("1");
        int count = tyjieguoMapper.countByExample(tyjieguoExample);
        return count >= TyConfig.Rule_PinzhongPinguiNum(ppxiangmuleixing, pinzhongxuhao).getNum();
    }

    @RequestMapping("vote")
    @ResponseBody
    public JsonResult<?> vote(@RequestParam("id") String ppdetailId,
            @RequestParam("pinguixuhao") String ppPinguixuhao,
            @RequestParam(value = "pinpaixuhao", required = false) String ppPinpaixuhao,
            @RequestParam(value = "pinzhongxuhao", required = false) String ppPinzhongxuhao,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            @RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("userid") String ppuserId,
            @RequestParam("result") String ppresult) {
        try {
            Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppxiangmuid);
            if (mmYsxiangmu.getIsactived() != 1) {
                return JsonResult.getErrorResult("表决失败，投票尚未启动");
            }
            if (TyConfig.hasRule_PinpaiOnlyPingui(ppxiangmuleixing) && ppresult.equals("1")) {
                if (VotePinguiAndPinpaiOnlyONE(ppxiangmuleixing, ppdetailId, ppxiangmuid, ppuserId)) {
                    return JsonResult.getErrorResult("必须且仅能选择一个品规");
                }
            }
            if (TyConfig.hasRule_PinpaiPinguiNum(ppxiangmuleixing) && ppresult.equals("1")) {
                if (VotePinguiAndPinpaiOnlyNum(ppdetailId, ppxiangmuid, ppuserId, ppxiangmuleixing)) {
                    if (TyConfig.Rule_PinpaiPinguiNum(ppxiangmuleixing, ppPinpaixuhao).getRequire())
                        return JsonResult.getErrorResult("必须且仅能选择"
                                + TyConfig.Rule_PinpaiPinguiNum(ppxiangmuleixing, ppPinpaixuhao).getNum() + "个品规");
                    else
                        return JsonResult.getErrorResult("最多能选择"
                                + TyConfig.Rule_PinpaiPinguiNum(ppxiangmuleixing, ppPinpaixuhao).getNum() + "个品规");

                }
            }
            if (TyConfig.hasRule_PinzhongPinguiNum(ppxiangmuleixing) && ppresult.equals("1")) {
                if (VotePinguiAndPinzhongOnlyNum(ppdetailId, ppxiangmuid, ppuserId, ppxiangmuleixing)) {
                    if (TyConfig.Rule_PinzhongPinguiNum(ppxiangmuleixing, ppPinzhongxuhao).getRequire())
                        return JsonResult.getErrorResult("必须且仅能选择"
                                + TyConfig.Rule_PinzhongPinguiNum(ppxiangmuleixing, ppPinzhongxuhao).getNum() + "个品规");
                    else
                        return JsonResult.getErrorResult("最多能选择"
                                + TyConfig.Rule_PinzhongPinguiNum(ppxiangmuleixing, ppPinzhongxuhao).getNum() + "个品规");

                }
            }
            if (TyConfig.hasRule_eliminated(ppxiangmuleixing) && ppresult.equals("1")) {
                Ty ty = tyMapper.selectByPrimaryKey(ppdetailId);
                if (ty.getIsvote() == 0)
                    return JsonResult.getErrorResult("该品规为淘汰品规");
            }
            if (((TyConfig.hasRule_needPinguiMax(ppxiangmuleixing) && ppresult.equals("1")
                    && mmYsxiangmu.getLunci() == 2)) || (ppxiangmuleixing.equals("212"))) {
                int[] tmp = VotePinguiMax(ppxiangmuid, ppxiangmuleixing, ppuserId);
                if (tmp[0] >= tmp[1]) {
                    return JsonResult.getErrorResult("最多能选择" + tmp[1] + "个品规");
                }
            }
            if (TyConfig.IsVotePinpai(ppxiangmuleixing)) {
                TyExample tyExample = new TyExample();
                List<Ty> tyList = tyMapper.selectByPinpai(TyConfig.getPinpai(ppxiangmuleixing), ppxiangmuid,
                        ppPinpaixuhao);
                for (Ty item : tyList) {

                    Tyjieguo mmjieguo = new Tyjieguo();
                    Tyjieguo mmuserjieguo = checkexistByUserId(item.getId(), ppuserId, ppxiangmuid);
                    if (mmuserjieguo != null) {// 已经存在
                        String mmId = mmuserjieguo.getId();
                        mmjieguo.setId(mmId);
                        mmjieguo.setResult(ppresult);
                        mmjieguo.setCreatetime(new Date());
                        if (tyjieguoMapper.updateByPrimaryKeySelective(mmjieguo) <= 0)
                            JsonResult.getErrorResult("表决失败");
                    } else {
                        mmjieguo.setId(UUID.randomUUID().toString());
                        mmjieguo.setDetailid(item.getId());
                        mmjieguo.setUserid(ppuserId);
                        mmjieguo.setResult(ppresult);
                        mmjieguo.setPinpai(ppPinpaixuhao);
                        mmjieguo.setPingui(ppPinguixuhao);
                        mmjieguo.setPinzhong(ppPinzhongxuhao); // 添加品种序号
                        mmjieguo.setCreatetime(new Date());
                        mmjieguo.setXiangmuid(ppxiangmuid);
                        if (tyjieguoMapper.insert(mmjieguo) <= 0)
                            JsonResult.getErrorResult("表决失败");
                    }
                }
            } else if (TyConfig.IsVotePinzhong(ppxiangmuleixing)) {
                TyExample tyExample = new TyExample();
                List<Ty> tyList = tyMapper.selectByPinzhong(TyConfig.getPinzhong(ppxiangmuleixing), ppxiangmuid,
                        ppPinzhongxuhao);
                for (Ty item : tyList) {
                    Tyjieguo mmjieguo = new Tyjieguo();
                    Tyjieguo mmuserjieguo = checkexistByUserId(item.getId(), ppuserId, ppxiangmuid);
                    if (mmuserjieguo != null) {// 已经存在
                        String mmId = mmuserjieguo.getId();
                        mmjieguo.setId(mmId);
                        mmjieguo.setResult(ppresult);
                        mmjieguo.setCreatetime(new Date());
                        if (tyjieguoMapper.updateByPrimaryKeySelective(mmjieguo) <= 0)
                            JsonResult.getErrorResult("表决失败");
                    } else {
                        mmjieguo.setId(UUID.randomUUID().toString());
                        mmjieguo.setDetailid(item.getId());
                        mmjieguo.setUserid(ppuserId);
                        mmjieguo.setResult(ppresult);
                        mmjieguo.setPinpai(ppPinpaixuhao);
                        mmjieguo.setPingui(ppPinguixuhao);
                        mmjieguo.setPinzhong(ppPinzhongxuhao); // 添加品种序号
                        mmjieguo.setCreatetime(new Date());
                        mmjieguo.setXiangmuid(ppxiangmuid);
                        if (tyjieguoMapper.insert(mmjieguo) <= 0)
                            JsonResult.getErrorResult("表决失败");
                    }
                }
            } else {

                Tyjieguo mmjieguo = new Tyjieguo();
                Tyjieguo mmuserjieguo = checkexistByUserId(ppdetailId, ppuserId, ppxiangmuid);
                if (mmuserjieguo != null) {// 已经存在
                    String mmId = mmuserjieguo.getId();
                    mmjieguo.setId(mmId);
                    mmjieguo.setResult(ppresult);
                    mmjieguo.setCreatetime(new Date());
                    return tyjieguoMapper.deleteByPrimaryKey(mmId) > 0 ? JsonResult.getSuccessResult("表决成功")
                            : JsonResult.getErrorResult("表决失败");
                } else {
                    mmjieguo.setId(UUID.randomUUID().toString());
                    mmjieguo.setDetailid(ppdetailId);
                    mmjieguo.setUserid(ppuserId);
                    mmjieguo.setResult(ppresult);
                    mmjieguo.setPinpai(ppPinpaixuhao);
                    mmjieguo.setPingui(ppPinguixuhao);
                    mmjieguo.setPinzhong(ppPinzhongxuhao); // 添加品种序号
                    mmjieguo.setCreatetime(new Date());
                    mmjieguo.setXiangmuid(ppxiangmuid);
                    return tyjieguoMapper.insert(mmjieguo) > 0 ? JsonResult.getSuccessResult("表决成功")
                            : JsonResult.getErrorResult("表决失败");
                }
            }
            return JsonResult.getSuccessResult("表决成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/vote:error", e);
            return JsonResult.getErrorResult("TyController/vote:error " + e.getMessage());
        }
    }

    @RequestMapping("getResultCount")
    @ResponseBody
    public JsonResult<?> getResultCount(@RequestParam("xiangmuid") String ppXiangmuId,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            @RequestParam("userid") String ppUserId) {
        try {

            Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppXiangmuId);
            if (mmYsxiangmu.getIsactived() != 1) {
                return JsonResult.getErrorResult("投票尚未启动");
            }
            List<Ysrenyuanfenpei> list = ddYsrenyuanfenpeiService.findbyUserIDandXiangmuId(ppUserId, ppXiangmuId);
            if (list.size() < 1) {
                return JsonResult.getErrorResult("人员-项目分配信息不存在");
            }
            int mmPass = countPass(ppxiangmuleixing, ppXiangmuId, ppUserId);
            int totalnum = countAll(ppxiangmuleixing, ppXiangmuId);

            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("qiyepass", mmPass);
            mmMap.put("totalnum", totalnum);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/getResultCount:error", e);
            return JsonResult.getErrorResult("TyController/getResultCount:error " + e.getMessage());
        }
    }

    @RequestMapping("submit")
    @ResponseBody
    public JsonResult<?> submit(@RequestParam("xiangmuid") String ppXiangmuId,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            @RequestParam("userid") String ppUserId) {
        try {
            Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppXiangmuId);
            if (mmYsxiangmu.getIsactived() != 1) {
                return JsonResult.getErrorResult("表决失败，投票尚未启动");
            }
            List<Ysrenyuanfenpei> list = ddYsrenyuanfenpeiService.findbyUserIDandXiangmuId(ppUserId, ppXiangmuId);
            if (list.size() < 1) {
                return JsonResult.getErrorResult("提交失败，人员-项目分配信息不存在");
            }
            if (TyConfig.hasRule_PinpaiOnlyPingui(ppxiangmuleixing)) {
                ArrayList<String> tmp = SubmitPinpaiOnlyONE(ppXiangmuId, ppxiangmuleixing, ppUserId);
                if (!tmp.isEmpty()) {
                    String str = String.join(",", tmp);
                    return JsonResult.getErrorResult("序号" + str + "必须选择一个品规");
                }
            }
            if (TyConfig.hasRule_PinpaiPinguiNum(ppxiangmuleixing)) {
                ArrayList<String> tmp = SubmitPinpaiNeedNum(ppXiangmuId, ppxiangmuleixing, ppUserId);
                if (!tmp.isEmpty()) {
                    String str = String.join(",", tmp);
                    return JsonResult.getErrorResult("序号" + str + "还需要继续选择品规");
                }
            }
            // if (TyConfig.hasRule_PinzhongPinguiNum(ppxiangmuleixing)) {
            // ArrayList<String> tmp = SubmitPinzhongNeedNum(ppXiangmuId, ppxiangmuleixing,
            // ppUserId);
            // if (!tmp.isEmpty()) {
            // String str = String.join(",", tmp);
            // return JsonResult.getErrorResult("序号" + str + "还需要继续选择品规");
            // }
            // }
            if (TyConfig.hasRule_NeedAll(ppxiangmuleixing)) {
                ArrayList<String> tmp = SubmitAll(ppXiangmuId, ppxiangmuleixing, ppUserId);
                if (!tmp.isEmpty()) {
                    String str = String.join(",", tmp);
                    return JsonResult.getErrorResult("序号" + str + "未选择");
                }
            }
            // if (TyConfig.hasRule_needPinguiMax(ppxiangmuleixing)) {
            // int[] tmp = SubmitPinguiMax(ppXiangmuId, ppxiangmuleixing, ppUserId);
            // if (tmp[0] >= tmp[1]) {
            // return JsonResult.getErrorResult("最多能选择" + tmp[1] + "个品规");
            // }
            // }

            Ysrenyuanfenpei mmRenyuanfenpei = ddYsrenyuanfenpeiService.findOne(list.get(0).getId());
            mmRenyuanfenpei.setIssubmit(1);
            mmRenyuanfenpei.setUpdatetime(new Date());
            mmRenyuanfenpei.setUpdateby(ppUserId);
            return ddYsrenyuanfenpeiService.update(mmRenyuanfenpei) == true ? JsonResult.getSuccessResult("提交成功")
                    : JsonResult.getErrorResult("提交失败");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/submit:error", e);
            return JsonResult.getErrorResult("TyController/submit:error " + e.getMessage());
        }
    }

    public ArrayList<String> SubmitAll(String ppXiangmuId, String ppxiangmuleixing, String ppUserId) {
        ArrayList<String> returnlist = new ArrayList<>();
        List<Ty> pinguiAll = tyMapper.findBiaojuelist(ppXiangmuId, ppUserId);
        List<Ty> pinpailist = pinguiAll.stream()
                .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                .collect(Collectors.toList());
        for (Ty item : pinpailist) {
            List<Ty> pinguiList = pinguiAll.stream().filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                    .equals(item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)))).collect(Collectors.toList());
            Optional<Ty> findAny = pinguiList.stream()
                    .filter(x -> (x.getResult() == null || Objects.equals(x.getResult(), "0"))).findFirst();
            if (findAny.isPresent()) {
                if (findAny.get().getIsvote() == 0)
                    break;
                returnlist.add(item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)));
            }
        }
        return returnlist;
    }

    public int[] SubmitPinguiMax(String ppXiangmuId, String ppxiangmuleixing, String ppUserId) {
        int maxnum = 147 - countPass("217", "05b23c14-772e-4947-b724-82e558905fad", ppUserId);
        int passnum = countPass(ppxiangmuleixing, ppXiangmuId, ppUserId);
        return new int[] { passnum, maxnum };
    }

    public int[] VotePinguiMax(String ppXiangmuId, String ppxiangmuleixing, String ppUserId) {
        int totalnum = countAll(ppxiangmuleixing, ppXiangmuId);
        int passnum = countPass(ppxiangmuleixing, ppXiangmuId, ppUserId);
        int maxnum = totalnum / 2;
        if (ppxiangmuleixing.equals("212"))
            maxnum = 1;
        return new int[] { passnum, maxnum, totalnum };
    }

    public ArrayList<String> SubmitPinpaiOnlyONE(String ppXiangmuId, String ppxiangmuleixing, String ppUserId) {
        ArrayList<String> returnlist = new ArrayList<>();
        List<Ty> pinguiAll = tyMapper.findBiaojuelist(ppXiangmuId, ppUserId);
        List<Ty> pinpailist = pinguiAll.stream()
                .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                .collect(Collectors.toList());
        for (Ty item : pinpailist) {
            List<Ty> pinguiList = pinguiAll.stream().filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                    .equals(item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)))).collect(Collectors.toList());
            Optional<Ty> findAny = pinguiList.stream().filter(x -> Objects.equals(x.getResult(), "1")).findFirst();
            if (findAny.isPresent()) {
            } else
                returnlist.add(item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)));
        }
        return returnlist;
    }

    public ArrayList<String> SubmitPinpaiNeedNum(String ppXiangmuId, String ppxiangmuleixing, String ppUserId) {
        ArrayList<String> returnlist = new ArrayList<>();
        List<Ty> pinguiAll = tyMapper.findBiaojuelist(ppXiangmuId, ppUserId);
        List<Ty> pinpailist = pinguiAll.stream()
                .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                .collect(Collectors.toList());
        for (Ty item : pinpailist) {
            List<Ty> pinguiList = pinguiAll.stream().filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                    .equals(item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)))).collect(Collectors.toList());
            Long count = pinguiList.stream().filter(x -> Objects.equals(x.getResult(), "1")).count();

            if (count < TyConfig
                    .Rule_PinpaiPinguiNum(ppxiangmuleixing, item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)))
                    .getNum()
                    && TyConfig.Rule_PinpaiPinguiNum(ppxiangmuleixing,
                            item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))).getRequire()) {
                returnlist.add(item.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)));
            }
        }
        return returnlist;
    }

    public ArrayList<String> SubmitPinzhongNeedNum(String ppXiangmuId, String ppxiangmuleixing, String ppUserId) {
        ArrayList<String> returnlist = new ArrayList<>();
        List<Ty> pinguiAll = tyMapper.findBiaojuelist(ppXiangmuId, ppUserId);
        List<Ty> pinzhonglist = pinguiAll.stream()
                .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                .collect(Collectors.toList());
        for (Ty item : pinzhonglist) {
            List<Ty> pinguiList = pinguiAll.stream().filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                    .equals(item.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing)))).collect(Collectors.toList());
            Long count = pinguiList.stream().filter(x -> Objects.equals(x.getResult(), "1")).count();

            if (count < TyConfig
                    .Rule_PinzhongPinguiNum(ppxiangmuleixing, item.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing)))
                    .getNum()
                    && TyConfig.Rule_PinzhongPinguiNum(ppxiangmuleixing,
                            item.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))).getRequire()) {
                returnlist.add(item.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing)));
            }
        }
        return returnlist;
    }

    @RequestMapping("voteAll")
    @ResponseBody
    public JsonResult<?> voteAll(@RequestParam("xiangmuid") String ppXiangmuId,
            @RequestParam("result") String ppResult,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            @RequestParam("userid") String ppUserId) {
        try {
            Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppXiangmuId);
            if (mmYsxiangmu.getIsactived() != 1) {
                return JsonResult.getErrorResult("表决失败，投票尚未启动");
            }
            tyjieguoMapper.deleteAll(ppXiangmuId, ppUserId);
            if (ppResult.equals("1")) {
                TyExample mmExample = new TyExample();
                mmExample.createCriteria().andXiangmuidEqualTo(ppXiangmuId).andIsvoteEqualTo(1);
                List<Ty> mmList = tyMapper.selectByExample(mmExample);
                List<Tyjieguo> addList = new ArrayList<>();
                List<Tyjieguo> updateList = new ArrayList<>();
                String pinpaixuhao = TyConfig.getPinpai(ppxiangmuleixing);
                String pinzhongxuhao = TyConfig.getPinzhong(ppxiangmuleixing);
                for (Ty ty : mmList) {
                    if (ty.getIsvote() == 0)
                        continue;
                    String mmid = ty.getId();
                    TyjieguoExample tyjieguoExample = new TyjieguoExample();
                    tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppXiangmuId).andUseridEqualTo(ppUserId)
                            .andDetailidEqualTo(mmid);
                    Tyjieguo mmjieguo = new Tyjieguo();
                    mmjieguo.setId(UUID.randomUUID().toString());
                    mmjieguo.setUserid(ppUserId);
                    mmjieguo.setDetailid(mmid);
                    mmjieguo.setResult(ppResult);
                    mmjieguo.setCreatetime(new Date());
                    mmjieguo.setXiangmuid(ppXiangmuId);
                    mmjieguo.setPingui(mmid);
                    mmjieguo.setPinpai(ty.getAttribute(pinpaixuhao));
                    mmjieguo.setPinzhong(ty.getAttribute(pinzhongxuhao));
                    addList.add(mmjieguo);
                }

                this.batchAddOrUpdate(addList, updateList);
            }

            return JsonResult.getSuccessResult("表决成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/voteAll:error", e);
            return JsonResult.getErrorResult("TyController/voteAll:error " + e.getMessage());
        }
    }

    @RequestMapping("findBiaojuelist")
    @ResponseBody
    public JsonResult<?> findBiaojuelist(@RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            @RequestParam("userid") String ppuserId,
            @RequestParam("drugname") String ppDrugname,
            @RequestParam("pageindex") int ppPageIndex,
            @RequestParam("pagesize") int ppPageSize) {
        try {
            Map<String, Object> mmReturnMap = new HashMap<String, Object>();
            Integer mmCount = countAll(ppxiangmuleixing, ppxiangmuId);
            Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppxiangmuId);
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 1) {

                int offset = (ppPageIndex - 1) * ppPageSize;
                RowBounds rowBounds = new RowBounds(offset, ppPageSize);
                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, ppuserId, rowBounds);
                mmReturnMap.put("pinguiList", mmPinguiAll);
                if (ppxiangmuleixing.equals("212")) {
                    mmReturnMap.put("totalcount", 2);
                    mmReturnMap.put("needcount", 1);
                    mmReturnMap.put("lunci", mmYsxiangmu.getLunci());
                    mmReturnMap.put("keshi", "共");
                }
            }
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 2) {
                List<Map<String, Object>> mmPinpaiList = new ArrayList<>();

                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, ppuserId);
                List<Ty> mmPinpailist = mmPinguiAll.stream()
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                        .collect(Collectors.toList());
                for (int i = 0; i < mmPinpailist.size(); i++) {
                    int mmPinguiHebingshu = 0;
                    Ty pinpaiONE = mmPinpailist.get(i);
                    Map<String, Object> mmPinguiMap = new HashMap<>();
                    mmPinguiMap.put("pinpaione", pinpaiONE);
                    mmPinguiMap.put("pinpaixuhao", pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing)));

                    List<Ty> mmPinguiList = mmPinguiAll.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                    .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    if (mmPinguiList.size() > 0) {
                        mmPinguiHebingshu = mmPinguiList.size();
                    } else {
                        mmPinguiHebingshu = mmPinguiHebingshu + 1;
                    }
                    mmPinguiMap.put("pinguiList", mmPinguiList);
                    mmPinguiMap.put("pinguihebinghang", mmPinguiHebingshu);
                    mmPinpaiList.add(mmPinguiMap);
                }

                mmReturnMap.put("pinpaiList", mmPinpaiList);
                mmReturnMap.put("pinpaixuhao", TyConfig.getPinpai(ppxiangmuleixing));
            }
            if (TyConfig.getXunhuan(ppxiangmuleixing) == 3) {
                List<Map<String, Object>> mmPinzhongList = new ArrayList<>();
                List<Ty> mmPinguiAll = tyMapper.findBiaojuelist(ppxiangmuId, ppuserId);
                // 修改：只按照品种字段进行去重，不再同时按品牌去重
                if (ppxiangmuleixing.equals("219")) {
                    int totalcount = countAll(ppxiangmuleixing, ppxiangmuId);
                    int needcount = TyConfig.Rule_PinzhongPinguiNumsp(ppxiangmuleixing,
                            mmPinguiAll.get(0).getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))).getNum();
                    if (mmYsxiangmu.getLunci() == 2) {
                        needcount = totalcount / 2;
                    }
                    mmReturnMap.put("totalcount", totalcount);
                    mmReturnMap.put("needcount", needcount);
                    mmReturnMap.put("lunci", mmYsxiangmu.getLunci());
                    mmReturnMap.put("keshi", mmPinguiAll.get(0).getText2());
                    if (mmYsxiangmu.getXiangmuid().equals("437c4666-f295-4ba6-b0cc-0040d60f9b42")
                            || mmYsxiangmu.getXiangmuid().equals("444c4666-f295-4ba6-b0cc-0040d60f9b42")) {
                        mmReturnMap.put("keshi", mmPinguiAll.get(0).getText2() + "," + mmPinguiAll.get(1).getText2()
                                + "," + mmPinguiAll.get(2).getText2() + "共");
                    }
                    mmReturnMap.put("pinzhongxuhao",
                            mmPinguiAll.get(0).getAttribute(TyConfig.getPinzhong(ppxiangmuleixing)));
                    mmReturnMap.put("pinpaixuhao",
                            mmPinguiAll.get(0).getAttribute(TyConfig.getPinpai(ppxiangmuleixing)));
                }
                List<Ty> mmPinzhonglist = mmPinguiAll.stream()
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                        .collect(Collectors.toList());
                for (int i = 0; i < mmPinzhonglist.size(); i++) {
                    int mmPinpaiHebingshu = 0;
                    List<Map<String, Object>> mmPinpaiList = new ArrayList<>();
                    Ty pinzhongONE = mmPinzhonglist.get(i);
                    Map<String, Object> mmPinpaiMap = new HashMap<>();
                    // 修改：使用pinzhongone而不是pinguione
                    mmPinpaiMap.put("pinzhongone", pinzhongONE);
                    // 修改：只按当前品种筛选，然后按品牌去重
                    List<Ty> mmPinpailist = mmPinguiAll.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                    .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                            .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    if (mmPinpailist.size() > 0) {
                        mmPinpaiHebingshu = mmPinpailist.size();
                    } else {
                        mmPinpaiHebingshu = mmPinpaiHebingshu + 1;
                    }
                    for (int j = 0; j < mmPinpailist.size(); j++) {
                        int mmPinguiHebingshu = 0;
                        Ty pinpaiONE = mmPinpailist.get(j);
                        Map<String, Object> mmPinguiMap = new HashMap<>();
                        mmPinguiMap.put("pinpaione", pinpaiONE);

                        // 修改：按当前品种和品牌同时筛选
                        List<Ty> mmPinguiList = mmPinguiAll.stream()
                                .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                        .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                                .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                        .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                                .collect(Collectors.toList());
                        if (mmPinguiList.size() > 0) {
                            mmPinguiHebingshu = mmPinguiList.size();
                        } else {
                            mmPinguiHebingshu = mmPinguiHebingshu + 1;
                        }
                        mmPinguiMap.put("pinguiList", mmPinguiList);
                        mmPinguiMap.put("pinguihebinghang", mmPinguiHebingshu);
                        mmPinpaiList.add(mmPinguiMap);
                    }
                    mmPinpaiMap.put("pinpaiList", mmPinpaiList);
                    mmPinpaiMap.put("pinguihebinghang", mmPinpaiHebingshu);
                    mmPinzhongList.add(mmPinpaiMap);
                }

                mmReturnMap.put("pinzhongList", mmPinzhongList);
                mmReturnMap.put("pinpaixuhao", TyConfig.getPinpai(ppxiangmuleixing));
                mmReturnMap.put("pinzhongxuhao", TyConfig.getPinzhong(ppxiangmuleixing));
            }
            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
            mmReturnMap.put("PageInfo", mmPageInfo);
            mmReturnMap.put("Xunhuan", TyConfig.getXunhuan(ppxiangmuleixing));
            mmReturnMap.put("getCount", TyConfig.getCount(ppxiangmuleixing));
            return JsonResult.getSuccessResult(mmReturnMap);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("TyController/findBiaojuelist:error", e);
            return JsonResult.getErrorResult("TyController/findBiaojuelist:error " + e.getMessage());
        }
    }

    @RequestMapping("qianzibiao")
    @ResponseBody
    public void qianzibiao(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            @RequestParam("userid") String ppuserid) {
        try {
            switch (TyConfig.getXunhuan(ppxiangmuleixing)) {
                case 1:
                    daochuqianzibiao1(ppxiangmuid, ppuserid, ppxiangmuleixing, request, response);// 语句
                    break; // 可选
                case 2:
                    daochuqianzibiao2(ppxiangmuid, ppuserid, ppxiangmuleixing, request, response);// 语句
                    break; // 可选
                case 3:
                    daochuqianzibiao3(ppxiangmuid, ppuserid, ppxiangmuleixing, request, response);// 语句
                    break; // 可选
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("huizongbiao")
    public void huizongbiao(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing) {
        try {
            switch (TyConfig.getXunhuan(ppxiangmuleixing)) {
                case 1:
                    daochuhuizongbiao1(request, response, ppxiangmuid, ppxiangmuleixing);// 语句
                    break; // 可选
                case 2:
                    daochuhuizongbiao2(request, response, ppxiangmuid, ppxiangmuleixing);// 语句
                    break; // 可选
                case 3:
                    daochuhuizongbiao3(request, response, ppxiangmuid, ppxiangmuleixing);// 语句
                    break; // 可选
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void daochuhuizongbiao1(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing) {
        List<Ysrenyuanfenpei> mmUserList = ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
        List<Ty> mmPinguiList = tyMapper.findBiaojuelist(ppxiangmuid, "");
        String xiangmumingcheng = ddYsxiangmuService.findOne(ppxiangmuid).getXiangmuname();
        Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppxiangmuid);
        Double mm = (TyConfig.getPassCount(ppxiangmuleixing)) * mmUserList.size();
        double mmTongguopiaoshu = mm;
        int exelend = TyConfig.getQianzibiaoEnd(ppxiangmuleixing);

        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        OutputStream os = null;
        WritableWorkbook wbook = null;

        try {
            os = new BufferedOutputStream(response.getOutputStream());// 得到输出流的语句
            // response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = xiangmumingcheng + StringHandle.tiemString(); // 文件名
            String tmptitle = xiangmumingcheng + "表决结果汇总表"; // 标题
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(wenjiantitle.getBytes(), "iso8859-1") + ".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = jxl.Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.ARIAL, 24, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);
            Label label = new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat = new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            // cellFormat.setBackground(Colour.AQUA);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            // wsheet.addCell(new Label(7, 0, tmptitle, wcfFC));
            wsheet.setRowView(0, 800); // 第一行高度
            wsheet.setRowView(1, 600); // 第二行高度
            wsheet.setRowView(2, 600); // 第二行高度
            if (TyConfig.IsTwoTitle(ppxiangmuleixing))
                wsheet.setRowView(3, 600); // 第二行高度
            wsheet.mergeCells(0, 0, exelend + 1, 0); // 合并单元格(第一列的第一行和第十三列的第一行合并)
            for (int i = 0; i < exelend; i++) {
                Integer columnWidth = TyConfig.getColumnView(ppxiangmuleixing)[i];
                wsheet.setColumnView(i, columnWidth != null ? columnWidth : 15);
            }
            wsheet.setColumnView(exelend, 15); // 宽度
            wsheet.setColumnView(exelend + 1, 15); // 宽度
            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 8, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setWrap(true);

            wsheet.addCell(new Label(exelend, 1, "日期:" + StringHandle.shorttiemString(), wcfFC2));
            wsheet.mergeCells(exelend, 1, exelend + 1, 1);
            if (!TyConfig.IsTwoTitle(ppxiangmuleixing)) {
                Map<Integer, String> titlemap = TyConfig.getExelTitle(ppxiangmuleixing);
                for (int i = 0; i < titlemap.size(); i++) {
                    wsheet.addCell(new Label(i, 2, titlemap.get(i + 1), wcfFC));
                }
                wsheet.addCell(new Label(titlemap.size(), 2, "委员表决票数", wcfFC));
                wsheet.addCell(new Label(titlemap.size() + 1, 2, "表决结果", wcfFC));
            } else {
                TyConfig.setTwoTitle(wsheet, wcfFC, ppxiangmuleixing, 2);
            }

            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            WritableCellFormat wcfFCb = new WritableCellFormat(wfont);
            wcfFCb.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFCb.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFCb.setAlignment(Alignment.CENTRE);
            wcfFCb.setWrap(true);
            wcfFCb.setBackground(Colour.GREEN);

            WritableCellFormat wcfFCr = new WritableCellFormat(wfont);
            wcfFCr.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFCr.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFCr.setAlignment(Alignment.CENTRE);
            wcfFCr.setWrap(true);
            wcfFCr.setBackground(Colour.RED);

            WritableCellFormat wcfFl = new WritableCellFormat(wfont);
            wcfFl.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFl.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFl.setAlignment(Alignment.LEFT);
            wcfFl.setWrap(true);

            int count = mmPinguiList.size();
            int mmpinguiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            TyjieguoExample tyjieguoExample = new TyjieguoExample();
            tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid);
            List<Tyjieguo> jieguo = tyjieguoMapper.selectByExample(tyjieguoExample);
            for (int i = 0; i < count; i++) {
                Ty pinguiOne = mmPinguiList.get(i);
                if (pinguiOne != null) {
                    String[] text = new String[26];
                    for (int k = 1; k < 26; k++) {
                        text[k] = pinguiOne.getAttribute("text" + k) == null ? ""
                                : pinguiOne.getAttribute("text" + k).toString();
                    }
                    long mmpiaoshu = jieguo.stream()
                            .filter(x -> x.getDetailid().equals(pinguiOne.getId()) && x.getResult().equals("1"))
                            .filter(distinctByKey(x -> x.getUserid())).count();

                    String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                    String mmJieguotext = "";
                    WritableCellFormat jieguocolor = new WritableCellFormat(wcfFC);

                    if (mmpiaoshu > mmTongguopiaoshu) {
                        mmJieguotext = "通过";
                        jieguocolor = wcfFCb;
                    } else {
                        mmJieguotext = "不通过";
                        jieguocolor = wcfFCr;
                    }
                    int k = 1;
                    if (TyConfig.SetRowHeight())
                        wsheet.setRowView(mmpinguiKaishihang, TyConfig.getRowHeight());
                    for (k = 1; k <= TyConfig.getQianzibiaoEnd(ppxiangmuleixing); k++) {
                        wsheet.addCell(new Label(k - 1, mmpinguiKaishihang, text[k], wcfFC));
                    }
                    wsheet.addCell(new Label(k - 1, mmpinguiKaishihang, piaoshutext, wcfFC));
                    wsheet.addCell(new Label(k, mmpinguiKaishihang, mmJieguotext, wcfFC));
                    mmpinguiKaishihang++;
                }

            }

            wbook.write(); // 写入文件
            wbook.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    public void daochuhuizongbiao3(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing) {
        List<Ysrenyuanfenpei> mmUserList = ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
        List<Ty> mmPinguiList = tyMapper.findBiaojuelist(ppxiangmuid, "");
        String xiangmumingcheng = ddYsxiangmuService.findOne(ppxiangmuid).getXiangmuname();
        TyjieguoExample tyjieguoExample = new TyjieguoExample();
        tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid);
        List<Tyjieguo> jieguolist = tyjieguoMapper.selectByExample(tyjieguoExample);
        Double mm = (TyConfig.getPassCount(ppxiangmuleixing)) * mmUserList.size();
        double mmTongguopiaoshu = mm;
        int exelend = TyConfig.getQianzibiaoEnd(ppxiangmuleixing);
        Ysxiangmu mmYsxiangmu = ddYsxiangmuService.findOne(ppxiangmuid);
        int count = mmPinguiList.size();
        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        OutputStream os = null;
        WritableWorkbook wbook = null;

        try {
            os = new BufferedOutputStream(response.getOutputStream());// 得到输出流的语句
            // response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = xiangmumingcheng + StringHandle.tiemString(); // 文件名
            String tmptitle = xiangmumingcheng + "结果汇总表"; // 标题
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(wenjiantitle.getBytes(), "iso8859-1") + ".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = jxl.Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.ARIAL, 24, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);
            Label label = new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat = new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            // cellFormat.setBackground(Colour.AQUA);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            // wsheet.addCell(new Label(7, 0, tmptitle, wcfFC));
            wsheet.setRowView(0, 800); // 第一行高度
            wsheet.setRowView(1, 600); // 第二行高度
            wsheet.setRowView(2, 600); // 第二行高度
            if (TyConfig.IsTwoTitle(ppxiangmuleixing))
                wsheet.setRowView(3, 600); // 第二行高度
            wsheet.mergeCells(0, 0, exelend + 1, 0); // 合并单元格(第一列的第一行和第十三列的第一行合并)
            for (int i = 0; i < exelend; i++) {
                Integer columnWidth = TyConfig.getColumnView(ppxiangmuleixing)[i];
                wsheet.setColumnView(i, columnWidth != null ? columnWidth : 15);
            }
            wsheet.setColumnView(exelend, 14); // 宽度
            wsheet.setColumnView(exelend + 1, 14); // 宽度

            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 8, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setWrap(true);

            wsheet.addCell(new Label(exelend, 1, "日期:" + StringHandle.shorttiemString(), wcfFC2));
            wsheet.mergeCells(exelend, 1, exelend + 1, 1);

            if (!TyConfig.IsTwoTitle(ppxiangmuleixing)) {
                Map<Integer, String> titlemap = TyConfig.getExelTitle(ppxiangmuleixing);
                for (int i = 0; i < titlemap.size(); i++) {
                    wsheet.addCell(new Label(i, 2, titlemap.get(i + 1), wcfFC));
                }
                wsheet.addCell(new Label(titlemap.size(), 2, "委员表决票数", wcfFC));
                wsheet.addCell(new Label(titlemap.size() + 1, 2, "表决结果", wcfFC));
            } else {
                TyConfig.setTwoTitle(wsheet, wcfFC, ppxiangmuleixing, 2);
            }

            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            WritableCellFormat wcfFCb = new WritableCellFormat(wfont);
            wcfFCb.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFCb.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFCb.setAlignment(Alignment.CENTRE);
            wcfFCb.setWrap(true);
            wcfFCb.setBackground(Colour.LIGHT_GREEN);

            WritableCellFormat wcfFCr = new WritableCellFormat(wfont);
            wcfFCr.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFCr.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFCr.setAlignment(Alignment.CENTRE);
            wcfFCr.setWrap(true);
            wcfFCr.setBackground(Colour.RED);

            if (ppxiangmuleixing.equals("219") && mmYsxiangmu.getLunci() == 1) {
                for (int i = 0; i < count; i++) {
                    Ty pinguiOne = mmPinguiList.get(i);
                    if (pinguiOne != null) {
                        long mmpiaoshu = jieguolist.stream()
                                .filter(x -> x.getDetailid().equals(pinguiOne.getId()) && x.getResult().equals("1"))
                                .filter(distinctByKey(x -> x.getUserid())).count();

                        String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                        String mmJieguotext = "";
                        WritableCellFormat jieguocolor = new WritableCellFormat(wcfFC);

                        if (mmpiaoshu > mmTongguopiaoshu) {
                            mmJieguotext = "通过";
                            jieguocolor = wcfFCb;
                        } else {
                            mmJieguotext = "不通过";
                            jieguocolor = wcfFCr;
                        }
                        pinguiOne.setResult(mmJieguotext);
                        pinguiOne.setPiaoshu(piaoshutext);
                    }

                }

                int passcount = (int) mmPinguiList.stream().filter(item -> "通过".equals(item.getResult())).count();
                int totalcount = countAll(ppxiangmuleixing, ppxiangmuid);
                String pinzhongxuhao = mmPinguiList.get(0).getAttribute(TyConfig.getPinzhong(ppxiangmuleixing));
                int needcount = TyConfig.Rule_PinzhongPinguiNumsp(ppxiangmuleixing, pinzhongxuhao).getNum();
                int num = needcount;
                if (passcount > num && num != 0) {
                    // 直接在mmPinguiAll中筛选和操作
                    // 获取通过的品规列表
                    List<Ty> passedList = mmPinguiList.stream()
                            .filter(item -> "通过".equals(item.getResult()))
                            .collect(Collectors.toList());

                    // 先将列表反转，这样原本靠后的项目会排在前面
                    Collections.reverse(passedList);

                    // 按照票数从低到高排序，票数相同时保持反转后的顺序（原本靠后的排在前面）
                    passedList.sort((item1, item2) -> {
                        // 获取票数
                        int votes1 = 0;
                        int votes2 = 0;

                        String piaoshu1 = item1.getPiaoshu();
                        if (piaoshu1 != null && piaoshu1.contains("/")) {
                            votes1 = Integer.parseInt(piaoshu1.split("/")[0]);
                        }

                        String piaoshu2 = item2.getPiaoshu();
                        if (piaoshu2 != null && piaoshu2.contains("/")) {
                            votes2 = Integer.parseInt(piaoshu2.split("/")[0]);
                        }

                        // 按票数升序排列
                        return votes1 - votes2;
                    });

                    // 计算需要设置为不通过的数量
                    int needToFailCount = passcount
                            - num;
                    // 将票数最低的needToFailCount个品规设为不通过
                    for (int i = 0; i < needToFailCount; i++) {
                        Ty item = passedList.get(i);
                        item.setResult("不通过");

                        // 确保在mmPinguiAll中也更新对应项的状态
//                        for (Ty originalItem : mmPinguiList) {
//                            if (originalItem.getId().equals(item.getId())) {
//                                originalItem.setResult("不通过");
//                                break;
//                            }
//                        }
                    }
                }
            }

            // 三层结构：品种-品牌-品规
            List<Ty> pinzhongList = mmPinguiList.stream()
                    .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                    .collect(Collectors.toList());
            int mmpinguiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int mmpinzhongKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int pinzhongcount = pinzhongList.size();

            for (int i = 0; i < pinzhongcount; i++) {
                Ty pinzhongONE = pinzhongList.get(i);

                // 获取当前品种下的所有品牌
                List<Ty> pinpaiList = mmPinguiList.stream()
                        .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                        .collect(Collectors.toList());

                int pinpaicount = pinpaiList.size();
                int mmPinzhongHebingshu = 0;
                int totalPinguiCount = 0;

                // 计算品种合并行数
                for (Ty pinpaiItem : pinpaiList) {
                    List<Ty> pinguiItems = mmPinguiList.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                    .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                            .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                    .equals(pinpaiItem.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    totalPinguiCount += pinguiItems.size();
                }

                mmPinzhongHebingshu = totalPinguiCount - 1;

                int mmpinpaiKaishihang = mmpinguiKaishihang;

                for (int j = 0; j < pinpaicount; j++) {
                    Ty pinpaiONE = pinpaiList.get(j);

                    // 获取当前品牌下的所有品规
                    List<Ty> pinguiList = mmPinguiList.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                    .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                            .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                    .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());

                    int pinguicount = pinguiList.size();
                    int mmPinpaiHebingshu = pinguicount - 1;

                    for (int k = 0; k < pinguicount; k++) {
                        Ty pinguiONE = pinguiList.get(k);
                        if (pinguiONE != null) {
                            String[] text = new String[26];
                            for (int m = 1; m < 26; m++) {
                                text[m] = pinguiONE.getAttribute("text" + m) == null ? ""
                                        : pinguiONE.getAttribute("text" + m).toString();
                            }
                            long mmpiaoshu = jieguolist.stream()
                                    .filter(x -> x.getDetailid().equals(pinguiONE.getId()) && x.getResult().equals("1"))
                                    .filter(distinctByKey(x -> x.getUserid())).count();

                            String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                            String mmJieguotext = "";
                            WritableCellFormat mmJieguocolor = wcfFC;

                            if (mmpiaoshu > mmTongguopiaoshu) {
                                mmJieguotext = "通过";
                                mmJieguocolor = wcfFCb;
                                // if (ppxiangmuleixing.equals("219") && mmYsxiangmu.getLunci() == 1
                                // && mmPinguiList.stream().filter(a -> a.getId().equals(pinguiONE.getId()))
                                // .findFirst().get().getResult().equals("不通过")) {
                                // mmJieguotext = "剔除";
                                // mmJieguocolor = wcfFCr;
                                // }
                            } else {
                                mmJieguotext = "不通过";
                                mmJieguocolor = wcfFCr;
                            }

                            if (TyConfig.SetRowHeight())
                                wsheet.setRowView(mmpinguiKaishihang, TyConfig.getRowHeight());

                            int m = 0;
                            for (m = 0; m < exelend; m++) {
                                // 检查是否应该添加单元格
                                // 判断当前列是否是品种列或品牌列
                                boolean isPinzhongColumn = false;
                                boolean isPinpaiColumn = false;

                                // 根据TyConfig配置判断是否为品种列或品牌列
                                if (TyConfig.isPinpaiLie(ppxiangmuleixing, m + 1)) {
                                    isPinpaiColumn = true;
                                }

                                // 根据TyConfig配置判断是否为品种列
                                if (TyConfig.isPinzhongLie(ppxiangmuleixing, m + 1)) {
                                    isPinzhongColumn = true;
                                }

                                // 如果是品种列且不是该品种的第一个品牌的第一个品规，则跳过
                                // 如果是品牌列且不是该品牌的第一个品规，则跳过
                                if ((j == 0 && k == 0) || (!isPinzhongColumn && !isPinpaiColumn) ||
                                        (k == 0 && !isPinzhongColumn) || (!isPinpaiColumn && !isPinzhongColumn)) {
                                    wsheet.addCell(new Label(m, mmpinguiKaishihang, text[m + 1], wcfFC));
                                }
                            }

                            if (!TyConfig.IsVotePinpai(ppxiangmuleixing)) {
                                wsheet.addCell(new Label(m, mmpinguiKaishihang, piaoshutext, wcfFC));
                                wsheet.addCell(new Label(m + 1, mmpinguiKaishihang, mmJieguotext, wcfFC));
                            }

                            mmpinguiKaishihang = mmpinguiKaishihang + 1;
                        }
                    }

                    // 合并品牌列
                    for (int g = 0; g < exelend; g++) {
                        if (TyConfig.isPinpaiLie(ppxiangmuleixing, g + 1)) {
                            wsheet.mergeCells(g, mmpinpaiKaishihang, g, mmpinpaiKaishihang + mmPinpaiHebingshu);
                        }
                    }

                    // 如果是投品牌，添加品牌的投票结果
                    if (TyConfig.IsVotePinpai(ppxiangmuleixing)) {
                        long mmpiaoshu = jieguolist.stream()
                                .filter(x -> x.getDetailid().equals(pinpaiONE.getId()) && x.getResult().equals("1"))
                                .filter(distinctByKey(x -> x.getUserid())).count();

                        String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                        String mmJieguotext = "";
                        WritableCellFormat mmJieguocolor = wcfFC;

                        if (mmpiaoshu > mmTongguopiaoshu) {
                            mmJieguotext = "通过";
                            mmJieguocolor = wcfFCb;
                        } else {
                            mmJieguotext = "不通过";
                            mmJieguocolor = wcfFCr;
                        }

                        wsheet.addCell(new Label(exelend, mmpinpaiKaishihang, piaoshutext, wcfFC));
                        wsheet.addCell(new Label(exelend + 1, mmpinpaiKaishihang, mmJieguotext, wcfFC));
                        wsheet.mergeCells(exelend, mmpinpaiKaishihang, exelend, mmpinpaiKaishihang + mmPinpaiHebingshu);
                        wsheet.mergeCells(exelend + 1, mmpinpaiKaishihang, exelend + 1,
                                mmpinpaiKaishihang + mmPinpaiHebingshu);
                    }

                    mmpinpaiKaishihang = mmpinpaiKaishihang + pinguicount;
                }

                // 合并品种列
                // 根据配置确定品种列
                for (int g = 0; g < exelend; g++) {
                    if (TyConfig.isPinzhongLie(ppxiangmuleixing, g + 1)) {
                        wsheet.mergeCells(g, mmpinzhongKaishihang, g, mmpinzhongKaishihang + mmPinzhongHebingshu);
                    }
                }

                // 如果是投品种，添加品种的投票结果
                if (TyConfig.IsVotePinzhong(ppxiangmuleixing)) {
                    long mmpiaoshu = jieguolist.stream()
                            .filter(x -> x.getDetailid().equals(pinzhongONE.getId()) && x.getResult().equals("1"))
                            .filter(distinctByKey(x -> x.getUserid())).count();

                    String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                    String mmJieguotext = "";
                    WritableCellFormat mmJieguocolor = wcfFC;

                    if (mmpiaoshu > mmTongguopiaoshu) {
                        mmJieguotext = "通过";
                        mmJieguocolor = wcfFCb;
                    } else {
                        mmJieguotext = "不通过";
                        mmJieguocolor = wcfFCr;
                    }

                    wsheet.addCell(new Label(exelend, mmpinzhongKaishihang, piaoshutext, wcfFC));
                    wsheet.addCell(new Label(exelend + 1, mmpinzhongKaishihang, mmJieguotext, wcfFC));
                    wsheet.mergeCells(exelend, mmpinzhongKaishihang, exelend,
                            mmpinzhongKaishihang + mmPinzhongHebingshu);
                    wsheet.mergeCells(exelend + 1, mmpinzhongKaishihang, exelend + 1,
                            mmpinzhongKaishihang + mmPinzhongHebingshu);
                }

                mmpinzhongKaishihang = mmpinzhongKaishihang + totalPinguiCount;
            }

            wbook.write(); // 写入文件
            wbook.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    public void daochuhuizongbiao2(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing) {
        List<Ysrenyuanfenpei> mmUserList = ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
        List<Ty> mmPinguiList = tyMapper.findBiaojuelist(ppxiangmuid, "");
        String xiangmumingcheng = ddYsxiangmuService.findOne(ppxiangmuid).getXiangmuname();

        Double mm = (TyConfig.getPassCount(ppxiangmuleixing)) * mmUserList.size();
        double mmTongguopiaoshu = mm;
        int exelend = TyConfig.getQianzibiaoEnd(ppxiangmuleixing);

        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        OutputStream os = null;
        WritableWorkbook wbook = null;

        try {
            os = new BufferedOutputStream(response.getOutputStream());// 得到输出流的语句
            // response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = xiangmumingcheng + StringHandle.tiemString(); // 文件名
            String tmptitle = xiangmumingcheng + "结果汇总表"; // 标题
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(wenjiantitle.getBytes(), "iso8859-1") + ".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = jxl.Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.ARIAL, 24, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);
            Label label = new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat = new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            // cellFormat.setBackground(Colour.AQUA);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            // wsheet.addCell(new Label(7, 0, tmptitle, wcfFC));
            wsheet.setRowView(0, 800); // 第一行高度
            wsheet.setRowView(1, 600); // 第二行高度
            wsheet.setRowView(2, 600); // 第二行高度
            if (TyConfig.IsTwoTitle(ppxiangmuleixing))
                wsheet.setRowView(3, 600); // 第二行高度
            wsheet.mergeCells(0, 0, exelend + 1, 0); // 合并单元格(第一列的第一行和第十三列的第一行合并)
            for (int i = 0; i < exelend; i++) {
                Integer columnWidth = TyConfig.getColumnView(ppxiangmuleixing)[i];
                wsheet.setColumnView(i, columnWidth != null ? columnWidth : 15);
            }
            wsheet.setColumnView(exelend, 14); // 宽度
            wsheet.setColumnView(exelend + 1, 14); // 宽度

            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 8, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setWrap(true);

            wsheet.addCell(new Label(exelend, 1, "日期:" + StringHandle.shorttiemString(), wcfFC2));
            wsheet.mergeCells(exelend, 1, exelend + 1, 1);

            if (!TyConfig.IsTwoTitle(ppxiangmuleixing)) {
                Map<Integer, String> titlemap = TyConfig.getExelTitle(ppxiangmuleixing);
                for (int i = 0; i < titlemap.size(); i++) {
                    wsheet.addCell(new Label(i, 2, titlemap.get(i + 1), wcfFC));
                }
                wsheet.addCell(new Label(titlemap.size(), 2, "委员表决票数", wcfFC));
                wsheet.addCell(new Label(titlemap.size() + 1, 2, "表决结果", wcfFC));
            } else {
                TyConfig.setTwoTitle(wsheet, wcfFC, ppxiangmuleixing, 2);
            }

            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            WritableCellFormat wcfFCb = new WritableCellFormat(wfont);
            wcfFCb.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFCb.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFCb.setAlignment(Alignment.CENTRE);
            wcfFCb.setWrap(true);
            wcfFCb.setBackground(Colour.LIGHT_GREEN);

            WritableCellFormat wcfFCr = new WritableCellFormat(wfont);
            wcfFCr.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFCr.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFCr.setAlignment(Alignment.CENTRE);
            wcfFCr.setWrap(true);
            wcfFCr.setBackground(Colour.RED);

            List<Ty> pinpaiList = mmPinguiList.stream()
                    .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                    .collect(Collectors.toList());
            int count = pinpaiList.size();
            int mmpinguiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int mmpinpaiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            TyjieguoExample tyjieguoExample = new TyjieguoExample();
            tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid);
            List<Tyjieguo> jieguolist = tyjieguoMapper.selectByExample(tyjieguoExample);

            for (int i = 0; i < count; i++) {
                Ty PinpaiONE = pinpaiList.get(i);

                int mmHebingshu = 0;

                List<Ty> mmPinguilist = mmPinguiList.stream()
                        .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                .equals(PinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                        .collect(Collectors.toList());
                if (mmPinguilist.size() > 0) {
                    mmHebingshu = mmPinguilist.size() - 1;
                }
                for (int j = 0; j < mmPinguilist.size(); j++) {
                    Ty pinguiONE = mmPinguilist.get(j);
                    if (pinguiONE != null) {
                        String[] text = new String[26];
                        for (int k = 1; k < 26; k++) {
                            text[k] = pinguiONE.getAttribute("text" + k) == null ? ""
                                    : pinguiONE.getAttribute("text" + k).toString();
                        }
                        long mmpiaoshu = jieguolist.stream()
                                .filter(x -> x.getDetailid().equals(pinguiONE.getId()) && x.getResult().equals("1"))
                                .filter(distinctByKey(x -> x.getUserid())).count();

                        String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                        String mmJieguotext = "";
                        WritableCellFormat mmJieguocolor = wcfFC;

                        if (mmpiaoshu > mmTongguopiaoshu) {
                            mmJieguotext = "通过";
                            mmJieguocolor = wcfFCb;
                        } else {
                            mmJieguotext = "不通过";
                            mmJieguocolor = wcfFCr;
                        }

                        if (TyConfig.SetRowHeight())
                            wsheet.setRowView(mmpinguiKaishihang, TyConfig.getRowHeight());
                        int k = 0;
                        for (k = 0; k < TyConfig.getQianzibiaoEnd(ppxiangmuleixing); k++) {
                            // 检查是否应该添加单元格，这里假设如果j==0或者不是品牌列，就添加
                            if (j == 0 || !TyConfig.isPinpaiLie(ppxiangmuleixing, k + 1)) {
                                wsheet.addCell(new Label(k, mmpinguiKaishihang, text[k + 1], wcfFC));
                            }
                        }
                        if (!TyConfig.IsVotePinpai(ppxiangmuleixing)) {

                            if (mmpiaoshu > mmTongguopiaoshu) {
                                mmJieguotext = "通过";
                                mmJieguocolor = wcfFCb;
                            } else {
                                mmJieguotext = "不通过";
                                mmJieguocolor = wcfFCr;
                            }

                            wsheet.addCell(new Label(k, mmpinguiKaishihang, piaoshutext, wcfFC));
                            wsheet.addCell(new Label(k + 1, mmpinguiKaishihang, mmJieguotext, wcfFC));
                        }
                        mmpinguiKaishihang = mmpinguiKaishihang + 1;
                    }
                }
                for (int g = 0; g < TyConfig.getQianzibiaoEnd(ppxiangmuleixing); g++) {
                    if (TyConfig.isPinpaiLie(ppxiangmuleixing, g + 1))
                        wsheet.mergeCells(g, mmpinpaiKaishihang, g, mmpinpaiKaishihang + mmHebingshu);
                }
                if (TyConfig.IsVotePinpai(ppxiangmuleixing)) {
                    long mmpiaoshu = jieguolist.stream()
                            .filter(x -> x.getDetailid().equals(PinpaiONE.getId()) && x.getResult().equals("1"))
                            .filter(distinctByKey(x -> x.getUserid())).count();

                    String piaoshutext = String.valueOf(mmpiaoshu) + "/" + String.valueOf(mmUserList.size());
                    String mmJieguotext = "";
                    WritableCellFormat mmJieguocolor = wcfFC;

                    if (mmpiaoshu > mmTongguopiaoshu) {
                        mmJieguotext = "通过";
                        mmJieguocolor = wcfFCb;
                    } else {
                        mmJieguotext = "不通过";
                        mmJieguocolor = wcfFCr;
                    }

                    wsheet.addCell(new Label(exelend, mmpinpaiKaishihang, piaoshutext, wcfFC));
                    wsheet.addCell(new Label(exelend + 1, mmpinpaiKaishihang, mmJieguotext, wcfFC));
                    wsheet.mergeCells(exelend, mmpinpaiKaishihang, exelend, mmpinpaiKaishihang + mmHebingshu);
                    wsheet.mergeCells(exelend + 1, mmpinpaiKaishihang, exelend + 1, mmpinpaiKaishihang + mmHebingshu);
                }

                mmpinpaiKaishihang = mmpinpaiKaishihang + mmHebingshu + 1;

            }

            wbook.write(); // 写入文件
            wbook.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    public void daochuqianzibiao1(@RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("userid") String ppuserid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            HttpServletRequest request, HttpServletResponse response) {

        response.reset();
        response.setContentType("application/x-download;charset=utf-8");

        int exelend = TyConfig.getQianzibiaoEnd(ppxiangmuleixing);

        List<Ty> mmList = tyMapper.findBiaojuelist(ppxiangmuid, ppuserid);

        // 在导出表第二行加一段字：本页投票结果：全部通过。/部分通过，不通过序号为：1、2...
        int mmCount = mmList.size();
        int mCount = 0;
        StringBuilder mmXuHaoBuilder = new StringBuilder("本页投票结果：部分通过，不通过序号为：");
        int length = mmXuHaoBuilder.length();
        for (Ty mmTy : mmList) {
            if (mmTy.getResult() == null) {
                mCount++;
                // 如果不是第一个失败的元素，则添加顿号
                if (mmXuHaoBuilder.length() > length) {
                    mmXuHaoBuilder.append("、");
                }
                mmXuHaoBuilder.append(mmTy.getText1().toString());
            }
        }
        // 如果所有元素都通过了检查，则设置mmWenZi为"全部通过。"
        // String mmWenZi = (mCount == 0) ? "本页投票结果：全部通过。" : mmXuHaoBuilder.toString();
        // 结束、mmWenZi

        String xiangmumingcheng = ddYsxiangmuService.findOne(ppxiangmuid).getXiangmuname();
        Ysuser mmuser = ddYsuserService.findOne(ppuserid);
        String mmusername = mmuser.getUsername();
        OutputStream os = null;
        WritableWorkbook wbook = null;
        try {
            os = new BufferedOutputStream(response.getOutputStream());// 得到输出流的语句
            // response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = xiangmumingcheng + mmusername + "委员结果表" + StringHandle.tiemString(); // 文件名
            String tmptitle = xiangmumingcheng; // 标题
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(wenjiantitle.getBytes(), "iso8859-1") + ".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = jxl.Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            SheetSettings settings = wsheet.getSettings();
            settings.setProtected(true);
            /* settings.setPassword("0000"); */
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.createFont("宋体"), 16, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);
            Label label = new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat = new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            // cellFormat.setBackground(Colour.AQUA);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            wsheet.setRowView(0, 600); // 第一行高度
            wsheet.setRowView(1, 600); // 第二行高度
            wsheet.setRowView(2, 600); // 第二行高度
            if (TyConfig.IsTwoTitle(ppxiangmuleixing))
                wsheet.setRowView(3, 600); // 第二行高度
            wsheet.mergeCells(0, 0, exelend, 0); // 合并单元格(第一列的第一行和第十三列的第一行合并)
            for (int i = 0; i < exelend; i++) {
                Integer columnWidth = TyConfig.getColumnView(ppxiangmuleixing)[i];
                wsheet.setColumnView(i, columnWidth != null ? columnWidth : 15);
            }
            wsheet.setColumnView(exelend, 14);

            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.createFont("方正小标宋简体"), 11, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);
            // 不需要边框和居中的样式
            WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setAlignment(Alignment.RIGHT);
            wcfFC2.setWrap(true);
            WritableCellFormat wcfFC22 = new WritableCellFormat(wfont2);
            wcfFC22.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC22 = new WritableCellFormat(wfont2);
            wcfFC22.setAlignment(Alignment.LEFT);
            wcfFC22.setWrap(true);
            // 在 1 列 2 行 写入内容
            wsheet.addCell(new Label(3, 1, "投票人(签字):投票内容已核对无误。" + mmusername, wcfFC2));
            // 把 0 列 2 行 到 9 列 2 行合并
            wsheet.mergeCells(3, 1, exelend-1, 1);

            wsheet.addCell(new Label(0, 1, "投票日期:" + StringHandle.shorttiemString(), wcfFC22));
            wsheet.mergeCells(0, 1, 2, 1);

            // 第三行 内容
            if (!TyConfig.IsTwoTitle(ppxiangmuleixing)) {
                Map<Integer, String> titlemap = TyConfig.getExelTitle(ppxiangmuleixing);
                for (int i = 0; i < titlemap.size(); i++) {
                    wsheet.addCell(new Label(i, 2, titlemap.get(i + 1), wcfFC));
                }
                wsheet.addCell(new Label(titlemap.size(), 2, "表决意见", wcfFC));
            } else {
                TyConfig.setTwoTitle(wsheet, wcfFC, ppxiangmuleixing, 1);
            }

            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.createFont("宋体"), 11, WritableFont.NO_BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);
            // 左对齐
            wfont2 = new jxl.write.WritableFont(WritableFont.createFont("宋体"), 11, WritableFont.NO_BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC2.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC2.setAlignment(Alignment.LEFT);
            wcfFC2.setWrap(true);
            int mmpinguiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int count = mmList.size();

            for (int i = 0; i < count; i++) {
                Ty pinguiOne = mmList.get(i);
                if (pinguiOne != null) {
                    String[] text = new String[26];
                    for (int k = 1; k < 26; k++) {
                        text[k] = pinguiOne.getAttribute("text" + k);
                    }

                    String mmresult = pinguiOne.getResult() == null ? "" : pinguiOne.getResult().toString();
                    String mmyijian = "";
                    if ("1".equals(mmresult)) {
                        mmyijian = "同意";
                    } else if ("0".equals(mmresult)) {
                        mmyijian = "不同意";
                    } else if (pinguiOne.getIsvote() == 1) {
                        mmyijian = "不同意";
                    } else {
                        mmyijian = "";
                    }
                    int k = 0;
                    if (TyConfig.SetRowHeight())
                        wsheet.setRowView(mmpinguiKaishihang, TyConfig.getRowHeight());
                    for (k = 0; k <= TyConfig.getQianzibiaoEnd(ppxiangmuleixing); k++) {
                        wsheet.addCell(new Label(k, mmpinguiKaishihang, text[k + 1], wcfFC));
                    }
                    wsheet.addCell(new Label(k - 1, mmpinguiKaishihang, mmyijian, wcfFC));
                    mmpinguiKaishihang++;
                }

            }
            wbook.write(); // 写入文件
            wbook.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public void daochuqianzibiao2(@RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("userid") String ppuserid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            HttpServletRequest request, HttpServletResponse response) {

        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        List<Ty> mmList = tyMapper.findBiaojuelist(ppxiangmuid, ppuserid);
        String xiangmumingcheng = ddYsxiangmuService.findOne(ppxiangmuid).getXiangmuname();
        int exelend = TyConfig.getQianzibiaoEnd(ppxiangmuleixing);
        Ysuser mmuser = ddYsuserService.findOne(ppuserid);
        String mmusername = mmuser.getUsername();
        OutputStream os = null;
        WritableWorkbook wbook = null;
        try {
            os = new BufferedOutputStream(response.getOutputStream());// 得到输出流的语句
            // response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = xiangmumingcheng + mmusername + "委员结果表" + StringHandle.tiemString(); // 文件名
            String tmptitle = xiangmumingcheng + "（" + mmusername + "）"; // 标题
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(wenjiantitle.getBytes(), "iso8859-1") + ".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = jxl.Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            SheetSettings settings = wsheet.getSettings();
            settings.setProtected(true);
            /* settings.setPassword("0000"); */
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.createFont("宋体"), 16, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);
            Label label = new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat = new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            // cellFormat.setBackground(Colour.AQUA);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            wsheet.setRowView(0, 600); // 第一行高度
            wsheet.setRowView(1, 600); // 第二行高度
            wsheet.setRowView(2, 600); // 第二行高度
            if (TyConfig.IsTwoTitle(ppxiangmuleixing))
                wsheet.setRowView(3, 600); // 第二行高度
            wsheet.mergeCells(0, 0, exelend, 0);
            for (int i = 0; i < exelend; i++) {
                Integer columnWidth = TyConfig.getColumnView(ppxiangmuleixing)[i];
                wsheet.setColumnView(i, columnWidth != null ? columnWidth : 15);
            }
            wsheet.setColumnView(exelend, 14);

            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.createFont("方正小标宋简体"), 11, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);
            // 不需要边框和居中的样式
            WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setAlignment(Alignment.RIGHT);
            wcfFC2.setWrap(true);
            WritableCellFormat wcfFC22 = new WritableCellFormat(wfont2);
            wcfFC22.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC22 = new WritableCellFormat(wfont2);
            wcfFC22.setAlignment(Alignment.LEFT);
            wcfFC22.setWrap(true);
            // 在 1 列 2 行 写入内容
            wsheet.addCell(new Label(3, 1, "投票人(签字):投票内容已核对无误。" + mmusername, wcfFC2));
            // 把 0 列 2 行 到 9 列 2 行合并
            wsheet.mergeCells(3, 1, exelend-1, 1);

            wsheet.addCell(new Label(0, 1, "投票日期:" + StringHandle.shorttiemString(), wcfFC22));
            wsheet.mergeCells(0, 1, 2, 1);

            // 第三行 内容
            if (!TyConfig.IsTwoTitle(ppxiangmuleixing)) {
                Map<Integer, String> titlemap = TyConfig.getExelTitle(ppxiangmuleixing);
                for (int i = 0; i < titlemap.size(); i++) {
                    wsheet.addCell(new Label(i, 2, titlemap.get(i + 1), wcfFC));
                }
                wsheet.addCell(new Label(titlemap.size(), 2, "表决意见", wcfFC));
            } else {
                TyConfig.setTwoTitle(wsheet, wcfFC, ppxiangmuleixing, 1);
            }

            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.createFont("宋体"), 11, WritableFont.NO_BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            List<Ty> pinpaiList = mmList.stream()
                    .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                    .collect(Collectors.toList());
            int mmpinguiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int mmpinpaiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int pinpaicount = pinpaiList.size();

            for (int i = 0; i < pinpaicount; i++) {
                Ty pinpaiONE = pinpaiList.get(i);
                List<Ty> pinguiList = mmList.stream().filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                        .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                        .collect(Collectors.toList());
                int pinguicount = pinguiList.size();
                int mmHebingshu = 0;
                if (pinguiList.size() > 0) {
                    mmHebingshu = pinguiList.size() - 1;
                }
                for (int j = 0; j < pinguicount; j++) {
                    Ty pinguiOne = pinguiList.get(j);
                    if (pinguiOne != null) {
                        String[] text = new String[26];
                        for (int k = 1; k < 26; k++) {
                            text[k] = pinguiOne.getAttribute("text" + k) == null ? ""
                                    : pinguiOne.getAttribute("text" + k).toString();
                        }

                        String mmresult = pinguiOne.getResult() == null ? "" : pinguiOne.getResult().toString();
                        String mmyijian = "";
                        if ("1".equals(mmresult)) {
                            mmyijian = "同意";
                        } else {
                            mmyijian = "不同意";
                        }
                        int m = 1;
                        if (TyConfig.SetRowHeight())
                            wsheet.setRowView(mmpinguiKaishihang, TyConfig.getRowHeight());
                        for (m = 0; m < exelend; m++) {
                            // 检查是否应该添加单元格，这里假设如果j==0或者不是品牌列，就添加
                            if (j == 0 || !TyConfig.isPinpaiLie(ppxiangmuleixing, m + 1)) {
                                wsheet.addCell(new Label(m, mmpinguiKaishihang, text[m + 1], wcfFC));
                            }
                        }
                        if (!TyConfig.IsVotePinpai(ppxiangmuleixing)) {
                            wsheet.addCell(new Label(m, mmpinguiKaishihang, mmyijian, wcfFC));
                        }
                        mmpinguiKaishihang = mmpinguiKaishihang + 1;
                    }
                }
                for (int g = 0; g < exelend; g++) {
                    if (TyConfig.isPinpaiLie(ppxiangmuleixing, g + 1))
                        wsheet.mergeCells(g, mmpinpaiKaishihang, g, mmpinpaiKaishihang + mmHebingshu);
                }
                if (TyConfig.IsVotePinpai(ppxiangmuleixing)) {
                    String mmresult = pinpaiONE.getResult() == null ? "" : pinpaiONE.getResult().toString();
                    String mmyijian = "";
                    if ("1".equals(mmresult)) {
                        mmyijian = "同意";
                    } else {
                        mmyijian = "不同意";
                    }

                    wsheet.addCell(new Label(exelend, mmpinpaiKaishihang, mmyijian, wcfFC));
                    wsheet.mergeCells(exelend, mmpinpaiKaishihang, exelend, mmpinpaiKaishihang + mmHebingshu);
                }
                mmpinpaiKaishihang = mmpinpaiKaishihang + mmHebingshu + 1;

            }
            wbook.write(); // 写入文件
            wbook.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public void daochuqianzibiao3(@RequestParam("xiangmuid") String ppxiangmuid,
            @RequestParam("userid") String ppuserid,
            @RequestParam("xiangmuleixing") String ppxiangmuleixing,
            HttpServletRequest request, HttpServletResponse response) {

        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        List<Ty> mmList = tyMapper.findBiaojuelist(ppxiangmuid, ppuserid);
        String xiangmumingcheng = ddYsxiangmuService.findOne(ppxiangmuid).getXiangmuname();
        int exelend = TyConfig.getQianzibiaoEnd(ppxiangmuleixing);
        Ysuser mmuser = ddYsuserService.findOne(ppuserid);
        String mmusername = mmuser.getUsername();

        // 获取用户列表
        List<Ysrenyuanfenpei> mmUserList = ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
        Double mm = (TyConfig.getPassCount(ppxiangmuleixing)) * mmUserList.size();
        Double mmTongguopiaoshu = mm;

        // 获取投票结果
        TyjieguoExample tyjieguoExample = new TyjieguoExample();
        tyjieguoExample.createCriteria().andXiangmuidEqualTo(ppxiangmuid);
        List<Tyjieguo> jieguoList = tyjieguoMapper.selectByExample(tyjieguoExample);

        OutputStream os = null;
        WritableWorkbook wbook = null;
        try {
            os = new BufferedOutputStream(response.getOutputStream());// 得到输出流的语句
            // response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = xiangmumingcheng + mmusername + "委员结果表" + StringHandle.tiemString(); // 文件名
            String tmptitle = xiangmumingcheng + "（" + mmusername + "）"; // 标题
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(wenjiantitle.getBytes(), "iso8859-1") + ".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = jxl.Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            SheetSettings settings = wsheet.getSettings();
            settings.setProtected(true);
            /* settings.setPassword("0000"); */
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.createFont("宋体"), 16, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            // wcfFC.setBackground(Colour.AQUA);
            Label label = new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat = new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            // cellFormat.setBackground(Colour.AQUA);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            wsheet.setRowView(0, 600); // 第一行高度
            wsheet.setRowView(1, 600); // 第二行高度
            wsheet.setRowView(2, 600); // 第二行高度
            if (TyConfig.IsTwoTitle(ppxiangmuleixing))
                wsheet.setRowView(3, 600); // 第二行高度
            wsheet.mergeCells(0, 0, exelend, 0);
            for (int i = 0; i < exelend; i++) {
                Integer columnWidth = TyConfig.getColumnView(ppxiangmuleixing)[i];
                wsheet.setColumnView(i, columnWidth != null ? columnWidth : 15);
            }
            wsheet.setColumnView(exelend, 14);

            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.createFont("方正小标宋简体"), 11, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(jxl.write.VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);
            // 不需要边框和居中的样式
//            WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false,
//                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式
//            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
//            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
//            wcfFC2 = new WritableCellFormat(wfont2);
//            wcfFC2.setWrap(true);
//            // 在 1 列 2 行 写入内容
//            wsheet.addCell(new Label(0, 1, "投票人(签字):投票内容已核对无误。" + mmusername, wcfFC2));
//            // 把 0 列 2 行 到 9 列 2 行合并
//            wsheet.mergeCells(0, 1, exelend - 3, 1);
//
//            wsheet.addCell(new Label(exelend - 2, 1, "投票日期:" + StringHandle.shorttiemString(), wcfFC2));
//            wsheet.mergeCells(exelend - 2, 1, exelend, 1);
            // 不需要边框和居中的样式
            WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK); // 设置表格样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC2 = new WritableCellFormat(wfont2);
            wcfFC2.setAlignment(Alignment.RIGHT);
            wcfFC2.setWrap(true);
            WritableCellFormat wcfFC22 = new WritableCellFormat(wfont2);
            wcfFC22.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 垂直居中
            wcfFC22 = new WritableCellFormat(wfont2);
            wcfFC22.setAlignment(Alignment.LEFT);
            wcfFC22.setWrap(true);
            // 在 1 列 2 行 写入内容
            wsheet.addCell(new Label(3, 1, "投票人(签字):投票内容已核对无误。" + mmusername, wcfFC2));
            // 把 0 列 2 行 到 9 列 2 行合并
            wsheet.mergeCells(3, 1, exelend-1, 1);

            wsheet.addCell(new Label(0, 1, "投票日期:" + StringHandle.shorttiemString(), wcfFC22));
            wsheet.mergeCells(0, 1, 2, 1);

            // 第三行 内容
            if (!TyConfig.IsTwoTitle(ppxiangmuleixing)) {
                Map<Integer, String> titlemap = TyConfig.getExelTitle(ppxiangmuleixing);
                for (int i = 0; i < titlemap.size(); i++) {
                    wsheet.addCell(new Label(i, 2, titlemap.get(i + 1), wcfFC));
                }
                wsheet.addCell(new Label(titlemap.size(), 2, "表决意见", wcfFC));
            } else {
                TyConfig.setTwoTitle(wsheet, wcfFC, ppxiangmuleixing, 1);
            }

            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.createFont("宋体"), 11, WritableFont.NO_BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); // 设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            // 三层结构：品种-品牌-品规
            List<Ty> pinzhongList = mmList.stream()
                    .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                    .collect(Collectors.toList());
            int mmpinguiKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int mmpinzhongKaishihang = TyConfig.getQianzibiaoStartRow(ppxiangmuleixing);
            int pinzhongcount = pinzhongList.size();

            for (int i = 0; i < pinzhongcount; i++) {
                Ty pinzhongONE = pinzhongList.get(i);

                // 获取当前品种下的所有品牌
                List<Ty> pinpaiList = mmList.stream()
                        .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                        .filter(distinctByKey(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                        .collect(Collectors.toList());

                int pinpaicount = pinpaiList.size();
                int mmPinzhongHebingshu = 0;
                int totalPinguiCount = 0;

                // 计算品种合并行数
                for (Ty pinpaiItem : pinpaiList) {
                    List<Ty> pinguiItems = mmList.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                    .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                            .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                    .equals(pinpaiItem.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());
                    totalPinguiCount += pinguiItems.size();
                }

                mmPinzhongHebingshu = totalPinguiCount - 1;

                int mmpinpaiKaishihang = mmpinguiKaishihang;

                for (int j = 0; j < pinpaicount; j++) {
                    Ty pinpaiONE = pinpaiList.get(j);

                    // 获取当前品牌下的所有品规
                    List<Ty> pinguiList = mmList.stream()
                            .filter(x -> x.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))
                                    .equals(pinzhongONE.getAttribute(TyConfig.getPinzhong(ppxiangmuleixing))))
                            .filter(x -> x.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))
                                    .equals(pinpaiONE.getAttribute(TyConfig.getPinpai(ppxiangmuleixing))))
                            .collect(Collectors.toList());

                    int pinguicount = pinguiList.size();
                    int mmPinpaiHebingshu = pinguicount - 1;

                    for (int k = 0; k < pinguicount; k++) {
                        Ty pinguiONE = pinguiList.get(k);
                        if (pinguiONE != null) {
                            String[] text = new String[26];
                            for (int m = 1; m < 26; m++) {
                                text[m] = pinguiONE.getAttribute("text" + m) == null ? ""
                                        : pinguiONE.getAttribute("text" + m).toString();
                            }

                            String mmresult = pinguiONE.getResult() == null ? "" : pinguiONE.getResult().toString();
                            String mmyijian = "";
                            if ("1".equals(mmresult)) {
                                mmyijian = "同意";
                            } else {
                                mmyijian = "不同意";
                            }

                            if (TyConfig.SetRowHeight())
                                wsheet.setRowView(mmpinguiKaishihang, TyConfig.getRowHeight());

                            int m = 0;
                            for (m = 0; m < exelend; m++) {
                                // 检查是否应该添加单元格
                                // 判断当前列是否是品种列或品牌列
                                boolean isPinzhongColumn = false;
                                boolean isPinpaiColumn = false;

                                // 根据TyConfig配置判断是否为品种列或品牌列
                                if (TyConfig.isPinpaiLie(ppxiangmuleixing, m + 1)) {
                                    isPinpaiColumn = true;
                                }

                                // 根据TyConfig配置判断是否为品种列
                                if (TyConfig.isPinzhongLie(ppxiangmuleixing, m + 1)) {
                                    isPinzhongColumn = true;
                                }

                                // 如果是品种列且不是该品种的第一个品牌的第一个品规，则跳过
                                // 如果是品牌列且不是该品牌的第一个品规，则跳过
                                if ((j == 0 && k == 0) || (!isPinzhongColumn && !isPinpaiColumn) ||
                                        (k == 0 && !isPinzhongColumn) || (!isPinpaiColumn && !isPinzhongColumn)) {
                                    wsheet.addCell(new Label(m, mmpinguiKaishihang, text[m + 1], wcfFC));
                                }
                            }

                            if (!TyConfig.IsVotePinpai(ppxiangmuleixing)
                                    && !TyConfig.IsVotePinzhong(ppxiangmuleixing)) {
                                wsheet.addCell(new Label(m, mmpinguiKaishihang, mmyijian, wcfFC));
                            }

                            mmpinguiKaishihang = mmpinguiKaishihang + 1;
                        }
                    }

                    // 合并品牌列
                    for (int g = 0; g < exelend; g++) {
                        if (TyConfig.isPinpaiLie(ppxiangmuleixing, g + 1)) {
                            wsheet.mergeCells(g, mmpinpaiKaishihang, g, mmpinpaiKaishihang + mmPinpaiHebingshu);
                        }
                    }

                    mmpinpaiKaishihang = mmpinpaiKaishihang + pinguicount;
                }

                // 合并品种列
                // 根据配置确定品种列
                for (int g = 0; g < exelend; g++) {
                    if (TyConfig.isPinzhongLie(ppxiangmuleixing, g + 1)) {
                        wsheet.mergeCells(g, mmpinzhongKaishihang, g, mmpinzhongKaishihang + mmPinzhongHebingshu);
                    }
                }

                // 如果是投品种，添加品种的投票结果
                if (TyConfig.IsVotePinzhong(ppxiangmuleixing)) {
                    String mmresult = pinzhongONE.getResult() == null ? "" : pinzhongONE.getResult().toString();
                    String mmyijian = "";
                    if ("1".equals(mmresult)) {
                        mmyijian = "同意";
                    } else {
                        mmyijian = "不同意";
                    }

                    wsheet.addCell(new Label(exelend, mmpinzhongKaishihang, mmyijian, wcfFC));
                    wsheet.mergeCells(exelend, mmpinzhongKaishihang, exelend,
                            mmpinzhongKaishihang + mmPinzhongHebingshu);
                }

                mmpinzhongKaishihang = mmpinzhongKaishihang + totalPinguiCount;
            }

            wbook.write(); // 写入文件
            wbook.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> map = new HashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {

            cell.setCellType(CellType.STRING);
            // 判断当前Cell的Type
            switch (cell.getCellType()) {

                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字
                        cell.setCellType(1);
                        // 取得当前Cell的数值
                        // cellvalue = String.valueOf(cell.getNumericCellValue());
                        cellvalue = cell.getStringCellValue();
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    public Tyjieguo checkexistByUserId(String ppId, String ppUserId, String ppxiangmuid) {
        TyjieguoExample mmExample = new TyjieguoExample();
        mmExample.createCriteria().andDetailidEqualTo(ppId).andUseridEqualTo(ppUserId).andXiangmuidEqualTo(ppxiangmuid);
        return tyjieguoMapper.selectByExample(mmExample).size() > 0 ? tyjieguoMapper.selectByExample(mmExample).get(0)
                : null;
    }

    public boolean isLogin(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session == null || session.getAttribute("Id") == null) {
            return false;
        }
        return true;
    }

    /**
     * Desc:
     * 批量插入数据
     *
     * @return
     */
    public void insertBatchThRead(List<Tyjieguo> recordList) {
        // 一个线程处理500条数据
        int count = 500;
        // 数据集合大小
        int listSize = recordList.size();
        // 开启的线程数
        int runSize = (listSize / count) + 1;
        // 存放每个线程的执行数据
        List<Tyjieguo> newList = null;
        // 创建一个线程池，数量和开启线程的数量一样
        ExecutorService executor = Executors.newFixedThreadPool(runSize);
        // 创建两个个计数器
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(runSize);

        // 开启的线程同时开始
        begin.countDown();
        for (int i = 0; i < runSize; i++) {
            /* 计算每个线程执行的数据 */
            if ((i + 1) == runSize) {
                int startIdx = (i * count);
                int endIdx = recordList.size();
                newList = recordList.subList(startIdx, endIdx);
            } else {
                int startIdx = (i * count);
                int endIdx = (i + 1) * count;
                newList = recordList.subList(startIdx, endIdx);
            }
            BatchInsertBankRecordThread thread = new BatchInsertBankRecordThread(newList, begin, end, tyjieguoMapper);
            executor.execute(thread);
        }
        try {
            end.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }

    public void updateBatchThRead(List<Tyjieguo> recordList) {
        // 一个线程处理500条数据
        int count = 500;
        // 数据集合大小
        int listSize = recordList.size();
        // 开启的线程数
        int runSize = (listSize / count) + 1;
        // 存放每个线程的执行数据
        List<Tyjieguo> newList = null;
        // 创建一个线程池，数量和开启线程的数量一样
        ExecutorService executor = Executors.newFixedThreadPool(runSize);
        // 创建两个个计数器
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(runSize);

        // 开启的线程同时开始
        begin.countDown();
        for (int i = 0; i < runSize; i++) {
            /* 计算每个线程执行的数据 */
            if ((i + 1) == runSize) {
                int startIdx = (i * count);
                int endIdx = recordList.size();
                newList = recordList.subList(startIdx, endIdx);
            } else {
                int startIdx = (i * count);
                int endIdx = (i + 1) * count;
                newList = recordList.subList(startIdx, endIdx);
            }
            BatchupdateBankRecordThread thread = new BatchupdateBankRecordThread(newList, begin, end, tyjieguoMapper);
            executor.execute(thread);
        }
        try {
            end.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }

    public void batchAddOrUpdate(List<Tyjieguo> mmaddList, List<Tyjieguo> mmupdateList) {

        List<Tyjieguo> addList = new ArrayList<>();
        List<Tyjieguo> updateList = new ArrayList<>();
        addList.addAll(mmaddList);
        updateList.addAll(mmupdateList);
        if (!addList.isEmpty()) {
            // 批量插入
            this.insertBatchThRead(addList);
        }
        if (!updateList.isEmpty()) {
            // 批量更新
            this.updateBatchThRead(updateList);
        }
    }
}
